Reactjs 如何在React中通过事件处理程序更新和使用状态

Reactjs 如何在React中通过事件处理程序更新和使用状态,reactjs,Reactjs,我有一个带有函数SearchArticle()的组件搜索器,它正确地使用了this.state.search,在组件装载后使用默认值(控制台显示搜索…:默认值)。但当我用handleKeyPress(e)更新this.state.search时,相同的函数SearchArticle()在更新为e.target值之前使用了prev state(控制台显示搜索…:再次默认)。我不知道怎么修 类搜索器扩展组件{ 建造师(道具){ 超级(道具); this.state={ 文章:[],搜索:“默认” }

我有一个带有函数SearchArticle()的组件搜索器,它正确地使用了this.state.search,在组件装载后使用默认值(控制台显示搜索…:默认值)。但当我用handleKeyPress(e)更新this.state.search时,相同的函数SearchArticle()在更新为e.target值之前使用了prev state(控制台显示搜索…:再次默认)。我不知道怎么修

类搜索器扩展组件{
建造师(道具){
超级(道具);
this.state={
文章:[],搜索:“默认”
}; 
}  
searchArticle(){
console.log('search…:',this.state.search)
}
手动按键=(e)=>{
如果(e.key=='Enter'){
this.setState({search:e.target.value});
这个.searchArticle();
}
}
componentDidMount(){
这个.searchArticle();
} 
render(){
返回(
搜索:
)
}
}

在执行
控制台.log
时,状态很可能尚未更新。这是因为
setState()
是异步的

因此,请尝试以下方法:

handleKeyPress = (e) => {
  if (e.key === 'Enter') {                            
    this.setState({search: e.target.value}, () => {
       this.searchArticle();
    });       
  }
}
我将您的
searchArticle()
移动到
setState()
回调中。这将保证在状态实际更新后执行


阅读有关
setState()
的更多信息

setState()
视为更新组件的请求,而不是即时命令。为了更好地感知性能,React可能会延迟它,然后在一次过程中更新多个组件。React不保证立即应用状态更改

setState()
并不总是立即更新组件。它可以批处理更新或将更新推迟到以后。这使得调用
setState()
后立即读取
This.state
成为一个潜在的陷阱。相反,使用
componentdiddupdate
setState
回调(
setState(updater,callback)
),这两种回调都保证在应用更新后触发

[……]

setState()
的第二个参数是一个可选的回调函数,在setState完成并重新呈现组件后将执行该函数