ReactJS - Need to click twice to set State and run function

前端 未结 3 1615
长发绾君心
长发绾君心 2021-01-02 06:40

Here is a summary of the code I have inside my React component:

getInitialState: function(){
  return{link:\"\"}
},
onClick1: function(){
   this.setState({         


        
3条回答
  •  隐瞒了意图╮
    2021-01-02 07:20

    From the docs:

    setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value.

    There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains.

    If you want a function to execute after the state transition completes, pass it in as a callback:

    onClick1: function() {
       this.setState({link:"Link1"}, this.otherFunction);
    },
    

提交回复
热议问题