简体   繁体   中英

Uncaught Error: A state mutation was detected between dispatches in React Native

I am getting this error A state mutation was detected between dispatches, in the path

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

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

Please Help me Resolve this issue.

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

Doing something like this:

const {checkboxes} = this.state;

is similar to:

const checkboxes = this.state.checkboxes;

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

Your checkboxes state is being mutated by the handlePressCheckedBox function.

Specifically, these lines are the culprits: checkboxes[indexParent1].sub_categories[index].status_code = 1; checkboxes[indexParent1].sub_categories[index].status_code = 0;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM