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

前端 未结 3 1616
长发绾君心
长发绾君心 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:13

    Well, here I am answering my own question, for future reference. I figured it out. I removed this.otherFunction() from the onClick functions, and put it in componentWillUpdate. So it looks like this:

    getInitialState: function(){
      return{link:""}
    },
    onClick1: function(){
       this.setState({link:"Link1"});
    },
    onClick2: function(){
       this.setState({link:"Link2"});
    },
    otherFunction:function(){
         //API call to this.state.link
    },
    componentWillUpdate(){
        this.otherFunction();
    },
    render: function(){
      return <div>
      <button1 onClick={this.onClick1}>Link1</button>
      <button2 onClick={this.onClick2}>Link2</button>
      //...some code to display the results of API call
      </div>
      }
    
    0 讨论(0)
  • 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);
    },
    
    0 讨论(0)
  • 2021-01-02 07:20

    If all that onClick does is change the state, then you shouldn't have two functions that do the same job. You should have the new value of the "link" state passed as an argument to the function "onClick" :)

    0 讨论(0)
提交回复
热议问题