我有一个组件,其中包含用户在文本框中插入内容时的处理程序函数。完成后,query
状态对象中的字段应设置为文本框的值。
例如,如果文本框为空,然后用户输入“s”,则handleInput()
中,我会做this.setState({event.target.value})
,应设置 this.state.query
到“s”。但这行不通。
当我输入“s”时,行 alert("setting query to "+this.state.query);
显示我 "setting query to"
,而不是预期的 "setting query to s"
。这对我来说真的很奇怪,因为 alert(event.target.value)
行打印出“s”,所以该值肯定在 event.target.value
中。
然后,如果我输入另一个字符,例如“a”,警报会显示“将查询设置为 s”。就好像this.state.query
一直落后1个字符。代码如下:
class Search extends Component {
constructor(props){
super(props);
let today = new Date();
this.state = {
searchSuggestion: 'Search for tweets here',
anchorEl: null,
date: today.toJSON(),
geocode: undefined,
page: 0,
placeName: 'the World',
query: ''
}
// Defining debounce is needed in constructor
this.searchTweets = debounce(500, this.searchTweets);
this.searchGeocode = debounce(500, this.searchGeocode);
}
componentDidMount() {
modelInstance.addObserver(this);
}
handleInput = event => {
alert("Handling input");
let query = event.target.value;
alert(event.target.value); // "s"
this.setState({
query: event.target.value
});
alert("setting query to "+this.state.query); // outputs "setting query to". this.state.query isn't set to anything!
let until = new Date(this.state.date);
this.searchTweets(query, this.state.geocode, until);
}
// Searches tweets until date
searchTweets = (query, location, date) => {
this.props.handleStatusChange('INITIAL');
modelInstance.searchTweets(query, location, date).then(result => {
modelInstance.setTweets(result);
this.props.handleStatusChange('LOADED');
this.setState({
data: result
});
}).catch(() => {
this.props.handleStatusChange('ERROR');
});
}
render(){
return(
<div className='search'>
<Row id='searchInput'>
<SearchInput handleInput={this.handleInput.bind(this)} searchInput={this.state.searchInput} searchSuggestion={this.state.searchSuggestion} page={1}/>
</Row>
<Row>
<SearchNav page={this.state.page}/>
</Row>
<Row id='date-location'>
<Col xs={2} sm={2} md={2} className='text'>
<p>UNTIL</p>
</Col>
<Col xs={4} sm={4} md={4} className='date'>
<SearchDate date={this.state.date} anchorEl={this.state.anchorEl} click={this.handleClick} dayChange={this.onDayChange}/>
</Col>
<Col xs={2} sm={2} md={2} className='text'>
<p>IN</p>
</Col>
<Col xs={4} sm={4} md={4} className='location'>
<SearchLocation placeName = {this.state.placeName} handleLocation={this.handleLocation.bind(this)}/>
</Col>
</Row>
</div>
)
}
}
export default Search;
怎么会出现这种情况?
最佳答案
发生这种情况是因为 state updates are asynchronous :
React may batch multiple
setState()
calls into a single update for performance.Because
this.props
andthis.state
may be updated asynchronously, you should not rely on their values for calculating the next state.
它说“this.props
和this.state
可能异步更新”但它应该几乎说将是,更新目前始终是异步的,它只是可能会也可能不会批处理。
如果您需要在更新 this.state
后执行某些操作,请使用 second argument ,这是更新时的回调。
关于javascript - 即使在 this.setState({query :value}) call,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50086851/