gpt4 book ai didi

javascript - 过滤对象数组并设置状态数组变量

转载 作者:行者123 更新时间:2023-11-29 20:37:27 25 4
gpt4 key购买 nike

这是我要按 orderId 过滤然后设置为状态变量的 JSON 输入。

[{"orderId":3,"userId":3,"firstName":"Amal","lastName":"kankanige","contactNo":"011-3456787","status":"pending","deliveryAddress":"No:24/c,Anders Road,Wijerama,Wijerama,Srilanka","productName":"Apple","quantity":2,"total":100.0,"id":null,"order_date":"2019-01-31 10:28:29"}]

这是我的状态。

  this.state = {
merchentOrders: [],
filterMerchentOrders: []
}

//这是方法

当我按 orderId 过滤时,它成功运行,然后我想将过滤后的输出设置为“this.setState({filterMerchentOrders: filterMerchentOrdersX});”。当我调出以下状态时,未设置值。

getOrderDetails = id => {

console.log("id ==" ,id);

let filterMerchentOrdersX = this.state.merchentOrders.filter(value => {
return (
value.orderId.toString()
.indexOf(id) !== -1

);
});

this.setState({filterMerchentOrders: filterMerchentOrdersX});

//this is working

console.log("filterMerchentOrdersX ==" ,filterMerchentOrdersX);

//this gives an empty array

console.log("this.state.filterMerchentOrders ==" ,this.state.filterMerchentOrders);
};

最佳答案

这可能是 setState 异步运行的原因,当您 console.log 时,值状态可能不会更新。

要查看更新后的状态,可以传递一个回调函数。

this.setState({filterMerchentOrders: filterMerchentOrdersX},()=>{
console.log("this.state.filterMerchentOrders ==" ,this.state.filterMerchentOrders);
})

关于javascript - 过滤对象数组并设置状态数组变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56424410/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com