简体   繁体   中英

Update state with setState ReactJs

I'm trying to update state variable when button click.but my issue is,it's update once with correct data then again it updated with constructor defined data.

    constructor(props) {
        super(props);
        this.state = {
            popupshow: [{ check: false, id: '' }]

        }
    }

componentDidUpdate(prevProps, prevState) {
         console.log("this.state.popupshow",this.state.popupshow)

    }


Details(type){
   this.state.popupshow[i].id = type
   this.state.popupshow[i].check = true;

   this.setState({ popupshow: this.state.popupshow });
}

render() {
return (
  <a onClick={() => this.Details("Tv Series")}>Update </>
)
}

my console.log is like bellow

在此处输入图片说明

I think you should rewrite details functions like :

Details(type, i){
   const popupDetail = Object.assign([], this.state.popupshow);
   popupDetail[i].id = type
   popupDetail[i].check = true;

   this.setState({ popupshow: popupDetail });
}

you are setting popupshow: this.state.popupshow this is causing forceupdate which re renders the component hence its value gets reset.

You should not update React state directly. You should always update/set React state via setState method.

These lines are against React principal

this.state.popupshow[i].id = type
this.state.popupshow[i].check = true;

Update your Details as follows

Details(type){
   let { popupshow } = this.state;
   let i = 0;
   popupshow[i].id = type
   popupshow[i].check = true;

   this.setState({ popupshow });
}

Note I dont have idea of variable i so assumed that as 0

I totally agree with the other answers have given for the question, however there are few things worth noting is you might wanna add the function to the context. The argument in favour of adding these lines to the constructor is so that the new bound functions are only created once per instance of the class. You could also use

onClick={this.Details.bind(this, "Tv Series")}

or (ES6):

onClick={() => this.Details("Tv Series")} but either of these methods will create a new function every time the component is re-rendered.

Then change the function to arrow fucntion too like

Details(type, i){
   const popupDetail = Object.assign([], this.state.popupshow);
   popupDetail[i].id = type
   popupDetail[i].check = true;

   this.setState({ popupshow: popupDetail });
}

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