用 Alt.js 错误并做出反应。不保留状态

Bug with Alt.js and react. State is not kept

我正在使用此 class 来显示和过滤列表。这 class 也会触发搜索。

我的问题是 setState 函数似乎不是即时的。

FriendActions.getSearchList(this.state.search);

如果我评论这个动作。 console.log 将按原样打印状态。 如果没有 'search' 状态将 "disappear"。

我认为可能在状态更改之前触发更改事件。但是我真的一点头绪都没有。

我希望我已经说清楚了。如果没有,请随时向我询问更多信息。

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);
  }

你需要改变你的逻辑。这样的事情应该有效:

onSearch(event){
  var search = event.target.value;

  if (search !== '') {
    FriendActions.getSearchList(search);
  }

  this.setState({search: search}); // w/ ES6: this.setState({search});
}

setState 不是即时的,你是对的。原因是您的代码中可以有很多 setState 调用。 React 将在 setState 上 运行 render。出于性能原因,它会等到所有 setState 调用完成后再呈现。

备选方案(不推荐): 手动设置您的状态

this.state = 'whatever';

更新自己

this.forceUpdate();