未捕获的错误:在 React Native 的调度之间检测到状态突变 [英] Uncaught Error: A state mutation was detected between dispatches in React Native
问题描述
我收到此错误在调度之间检测到状态突变,在路径中
我在 componentWillReceiveProps 中使用了 setState :
I have used setState in componentWillReceiveProps :
this.setState({ checkboxes: nextProps.data.my_details});
在渲染函数中,我生成了动态复选框,并根据我得到的值显示复选框是否选中.见下面的代码:
In render function i have generated dynamic checkboxes and based on the value i am getting i am showing checkbox checked or not. see code below :
renderSubCategory(data, indexParent){
let indexParent1 = indexParent;
const {checkboxes} = this.state;
return checkboxes[indexParent1].sub_categories.map((data1, index1) => {
return(
<View key={index1}>
<View style={{ flex: 1, flexDirection: 'column' }}>
<CheckBox
label={data1.name}
labelStyle={{fontSize:14}}
size={25}
color='#17bb8f'
checked={data1.status_code === 0 ? false : true}
onPress={(checked)=>this.handlePressCheckedBox(index1, checked, indexParent1)}
/>
</View>
</View>
)
})
}
现在复选框的 onPress 功能我正在更改复选框的状态并出现突变错误.
Now onPress function of checkbox i am changing the state of checkbox and getting mutation error.
handlePressCheckedBox = (index,checked, indexParent1) => {
const {checkboxes} = this.state;
if(checkboxes[indexParent1].sub_categories[index].status_code === 0){
checkboxes[indexParent1].sub_categories[index].status_code = 1;
}else{
checkboxes[indexParent1].sub_categories[index].status_code = 0;
}
this.setState({
checkboxes
});
}
请帮我解决这个问题.
推荐答案
我觉得问题出在这部分代码:
I think the problem comes from this part of code:
const {checkboxes} = this.state;
if(checkboxes[indexParent1].sub_categories[index].status_code === 0){
checkboxes[indexParent1].sub_categories[index].status_code = 1;
}else{
checkboxes[indexParent1].sub_categories[index].status_code = 0;
}
做这样的事情:
const {checkboxes} = this.state;
类似于:
const checkboxes = this.state.checkboxes;
之后,当你改变status_code时,你手动改变状态而不是使用setState(引用被改变).
After that, when you change the status_code, you change manually the state instead of using the setState (the reference is changed).
解决方案:使用扩展迭代器传递状态的副本而不是状态引用
Solution: Use a spread iterator to pass a copy of your state instead of your state reference
const checkboxes = {...this.state.checkboxes};
这篇关于未捕获的错误:在 React Native 的调度之间检测到状态突变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!