【问题标题】:setState not updating state even with callback and handleFunction - ReactJs即使使用回调和 handleFunction,setState 也不会更新状态 - ReactJs
【发布时间】:2021-07-09 20:46:16
【问题描述】:

我有一个在另一个组件中调用的句柄函数。这会传递一个名为 data 的值,我想将其更新到我的 state

//basic code
initialState = {
  wordCount:"Some Value"
  text: "Some value"
}
class Home extends Component{
  state = initialState;
  handler(data){
    console.log('Arrived',data)
    this.setState({wordCount:data,text:GetText(data,this.state)});
    this.validation();
  }
  validation(){
    console.log(this.state.wordCount)
  }
  render(){
  return (
      <div><Component handlerFunc={this.handler.bind(this)}</div>
  )
  }
       

在我的处理函数中打印出data 我确实收到了正确的信息作为字符串。我使用 setState 将wordCount 的初始值替换为data。我对text 做同样的事情。 GetText 返回一个字符串。

但是当验证运行时,我的状态是完全一样的。这怎么可能?

【问题讨论】:

    标签: javascript reactjs state


    【解决方案1】:

    注意:react 中的 setState 是异步的。

    这意味着不能保证状态会在下一条语句中改变。你可以做些什么来避免这种情况是 setState 接受回调,它将在设置状态完成时调用。

    this.setState(
       {
           wordCount:data,
           text:GetText(data,this.state)
       }, 
       () => { 
        // Gets called when setState updates the state
        this.validation() 
    });
    
    

    【讨论】:

    • 好的。但是不再调用 validate (验证函数只是 console.logs this.state.wordCount 。我看不到输出,因为我改变了这个。我做错了什么。
    • @BuddyBob 您可能在使用this 时遇到问题。尝试访问回调中的状态或使用控制台日志。你会看到状态肯定会改变
    • 我从来没有和this搞过。怎么可能不正确。此外,在我的回调中,我正在运行验证。其中有一个 console.log()。看来它一开始就没有运行过。
    • @BuddyBob Arrived 是否以上面示例的控制台形式打印?然后你会在代码中得到 console.log() 。如果什么都没有,那么您可能在 GetText(data,this.state) 该函数中遇到了错误。尝试使用错误处理程序,看看是否有任何错误
    • 疯了吧。我单独调用 GetText,当我 console.log 时工作正常。 Arrived 也会被记录。我的大脑很痛。
    猜你喜欢
    • 2020-01-30
    • 2019-12-21
    • 1970-01-01
    • 1970-01-01
    • 2020-10-25
    • 1970-01-01
    • 2023-01-19
    • 2017-07-23
    • 2018-08-05
    相关资源
    最近更新 更多