我使用这个类来显示和过滤一个列表。这个类还会触发搜索。
我的问题是,setState函数似乎不是即时的。
FriendActions.getSearchList(this.state.search);如果我评论这个行为。console.log将按原样打印状态。如果没有,‘搜索’状态将“消失”。
我想一个变化的事件可能是在国家改变之前的火。但我真的毫无头绪。
我希望我已经说清楚了。如果没有,可以自由地问我更多的信息。
onSearch(event){
this.setState({search: event.target.value});
if (this.state.search !== '')
FriendActions.getSearchList(this.state.search);
}
class FriendList extends React.Component {
constructor(props) {
super(props);
this.state = FriendStore.getState();
this.onChange = this.onChange.bind(this);
this.filterByUsername = this.filterByUsername.bind(this);
// limit this function every 200 ms
this.onSearch = debounce(this.onSearch, 200);
}
componentDidMount () {
FriendStore.listen(this.onChange);
FriendActions.getFriendsList();
}
componentWillUnmount() {
FriendStore.unlisten(this.onChange);
}
onChange(state) {
console.log(state);
this.setState(state);
}
onSearch(event){
this.setState({search: event.target.value});
if (this.state.search !== '')
FriendActions.getSearchList(this.state.search);
}发布于 2015-10-29 14:11:19
你需要改变你的逻辑。像这样的事情应该有效:
onSearch(event){
var search = event.target.value;
if (search !== '') {
FriendActions.getSearchList(search);
}
this.setState({search: search}); // w/ ES6: this.setState({search});
}setState不是即时的,这一点是正确的。原因是您可以在代码中包含许多setState调用。React将在render上运行setState。出于性能原因,它一直等到所有setState调用完成后才呈现。
替代解决方案(不推荐):手动设置状态
this.state = 'whatever';更新你自己
this.forceUpdate();https://stackoverflow.com/questions/33414572
复制相似问题