【问题标题】:Uncaught Error: A state mutation was detected between dispatches in React Native未捕获的错误:在 React Native 中的调度之间检测到状态突变
【发布时间】:2017-03-16 12:49:29
【问题描述】:

我收到此错误在路径中的调度之间检测到状态突变

我在 componentWillReceiveProps 中使用了 setState :

this.setState({ checkboxes: nextProps.data.my_details});

在渲染函数中,我生成了动态复选框,并根据我得到的值显示复选框是否选中。见下面的代码:

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 函数我正在更改复选框的状态并出现突变错误。

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
    });
 }

请帮我解决这个问题。

【问题讨论】:

    标签: reactjs react-native react-redux


    【解决方案1】:

    我认为问题出在这部分代码:

    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(引用已更改)。

    解决方案: 使用传播迭代器传递您的状态副本而不是您的状态引用

    const checkboxes = {...this.state.checkboxes};
    

    【讨论】:

    • 感谢@jpclair 的回复,我知道问题出在我更改状态的那一行。我也尝试了您给出的解决方案,但仍然出现突变错误。你能帮我解决这个问题吗?
    【解决方案2】:

    checkboxes 函数正在改变您的 checkboxes 状态。

    具体来说,这些行是罪魁祸首: checkboxes[indexParent1].sub_categories[index].status_code = 1; checkboxes[indexParent1].sub_categories[index].status_code = 0;

    【讨论】:

    • 感谢@Derek 的回复。我知道。你有什么解决办法吗?
    猜你喜欢
    • 1970-01-01
    • 2017-04-24
    • 2019-12-25
    • 2019-10-13
    • 2017-11-04
    • 2016-12-08
    • 1970-01-01
    • 2017-07-17
    • 1970-01-01
    相关资源
    最近更新 更多