【问题标题】:ReactJS - Need to click twice to set State and run functionReactJS - 需要点击两次才能设置状态和运行功能
【发布时间】:2016-01-14 22:19:58
【问题描述】:

以下是我的 React 组件中的代码摘要:

getInitialState: function(){
  return{link:""}
},
onClick1: function(){
   this.setState({link:"Link1"});
   this.otherFunction();
},
onClick2: function(){
   this.setState({link:"Link2"});
   this.otherFunction();
},
otherFunction:function(){
     //API call to this.state.link
},
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>
  }

我遇到的问题是第一次单击按钮时,otherFunction 会运行,但它不会有 myState 的更新值。如果我再次单击,则它可以正常工作。

【问题讨论】:

  • setState 正在触发渲染; otherFunction 是什么?它应该更新什么状态?
  • API 数据还有另一种状态。这就是功能正在更新的内容。我没有在此处包含它,因为我认为它不相关。

标签: reactjs


【解决方案1】:

来自docs

setState() 不会立即改变this.state,而是创建一个挂起的状态转换。调用此方法后访问this.state 可能会返回现有值。

无法保证对 setState 的调用同步操作,并且可能会批量调用以提高性能。

如果您希望函数在状态转换完成后执行,请将其作为回调传入:

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

【讨论】:

  • 感谢您的解释。不幸的是,将函数作为回调不起作用。编辑:我看过一些例子,听起来应该可以。不知道为什么我的不是。我会再看一遍。
  • 有点不相关,otherFunction 可能未绑定;这可能会更好:this.SetState(/*...*/, () =&gt; this.otherFunction() ).
【解决方案2】:

好吧,我在这里回答我自己的问题,以供将来参考。 我想到了。我从 onClick 函数中删除了 this.otherFunction(),并将其放入 componentWillUpdate 中。所以它看起来像这样:

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

【讨论】:

    【解决方案3】:

    如果 onClick 所做的只是改变状态,那么你不应该有两个函数做同样的工作。您应该将“链接”状态的新值作为参数传递给函数“onClick”:)

    【讨论】:

      猜你喜欢
      • 2021-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-08
      • 1970-01-01
      • 2023-03-17
      • 2011-03-15
      相关资源
      最近更新 更多