[英]React state is undefined , even though console.log shows it
I have researched other cases when the state was unidentified but I am still unsuccessfully trying to subtract data from UI actions that is in the format [{},{}...].我研究了 state 无法识别的其他情况,但我仍然未能成功尝试从格式为 [{},{}...] 的 UI 操作中减去数据。 I have managed to add to the array, using this code, which in the same time also computes the total for the item (subTotal and products are props from a child component got through a callback function):我已经设法使用此代码添加到数组中,同时它还计算项目的总数(subTotal 和 products 是通过回调函数获得的子组件的道具):
const updateTotalPriceAndUpdatePieChartData = (subTotal,product) => {
//from here
setPieChartData([...pieChartData,{product,subTotal}])
//until up, we handle what data we need for the pieChart
setTotal(total => total + (Number.isFinite(subTotal) ? subTotal : 0))
console.log("TOTAL WAS COMPUTED")
}
And this is the state that holds the array:这是保存数组的 state:
const [pieChartData,setPieChartData]=React.useState([])
Yet when I try to delte an object from the state array (when an item is also deleted), I try the following:然而,当我尝试从 state 数组中删除一个 object 时(当一个项目也被删除时),我尝试以下操作:
const substractSubTotalAndSubstractTotalForPieChart = (subTotal,product,pieChartData) => {
setTotal(total - subTotal)
const lastPieChartData=pieChartData.filter(item => item !={subTotal,product})
setPieChartData(lastPieChartData)
}
It says that pieChartData
is unidentified.它说pieChartData
身份不明。 Could you please let me know what I can do?你能告诉我我能做什么吗?
In substractSubTotalAndSubstractTotalForPieChart
method, there is a paramter pieChartData
, but there is also a state
with the same name .在substractSubTotalAndSubstractTotalForPieChart
方法中,有一个参数pieChartData
,但也有一个同名的state
。 So what happens is inside the function substractSubTotalAndSubstractTotalForPieChart's
scope, the parameter pieChartData
is given preference rather than the state.所以在 function substractSubTotalAndSubstractTotalForPieChart substractSubTotalAndSubstractTotalForPieChart's
scope 内部会发生什么,参数pieChartData
优先于 Z9ED39E2EA931586B76A985A69E24。
Hence in your method invocation, when you don't pass this parameter, the default value of an uninitialized parameter, ie, undefined is used.因此,在您的方法调用中,当您不传递此参数时,将使用未初始化参数的默认值,即 undefined。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.