首页 > 解决方案 > Reactjs setState 异步

问题描述

我正在构建一个小搜索引擎并遇到以下问题:

每次我输入查询时,最后一个字母都会丢失。我发现,它与setState有关,并且它不是异步的……但我无法为我的案例提出解决方案。

她是我的功能:

  searchHandler = ({ target: { value } }) => {

  this.setState({ term: value });
    this.updateMessage(value);

    if(this.state.message.length === 0){
      this.setState({hasMoreItems: false})

      this.componentDidMount();
    }else{

  var requestUrl = 'https://questdb.herokuapp.com/all?q='
  fetch(requestUrl + this.state.message).then((response)=>{
      return response.json();
  }) .then((data)=>{
      this.setState({ tracks: data});

  })
}
}


updateMessage = message => this.setState({ message });

你对我有什么建议吗?

非常感谢!

标签: reactjsasynchronousfetchsetstate

解决方案


this.setState()可以传递一个回调函数,该函数将在状态实际设置为新值后执行。你可以像这样使用它:

this.setState({something: newValue}, () => {
    console.log(this.state.something) // this will print out the new value
});

推荐阅读