Reactjs setState 异步 [英] Reactjs setState asynchronous
本文介绍了Reactjs setState 异步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在构建一个小型搜索引擎并遇到以下问题:
I am building a little search engine and got following problem:
每次我输入查询时,最后一个字母都会丢失.我发现它与 setState 有关,并且它不是 异步...但我无法为我的情况提出解决方案.
Everytime I enter a query, the last letter is missing. I figured out, that it has something to do with setState and that it is not asynchronous... But I can not come up with a solution fo my case.
她是我的职责:
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 });
你对我有什么建议吗?
非常感谢!
推荐答案
一般情况下,您希望使用 setState()
的第二个参数,它接受一个回调函数,该函数将在更新后运行状态.这是一个例子:
In general, you want to use the second argument of setState()
, which accepts a callback function which will run with the updated state. Here's an example:
import React, { Component } from 'react';
import { render } from 'react-dom';
class App extends React.Component {
state = {
value: '',
}
handleChange = (e) => {
e.preventDefault();
const { value } = e.target;
this.setState({ value }, () => {
console.log('Value is:', this.state.value );
})
}
render() {
return (
<input value={this.state.value} onChange={this.handleChange} />
)
}
}
render(<App />, document.getElementById('root'));
现场示例这里.
这篇关于Reactjs setState 异步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文