【问题标题】:Bug with Alt.js and react. State is not keptAlt.js 的错误并做出反应。不保存状态
【发布时间】:2016-01-29 14:45:25
【问题描述】:

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

我的问题是 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);
  }

【问题讨论】:

    标签: reactjs flux alt.js


    【解决方案1】:

    你需要改变你的逻辑。像这样的东西应该可以工作:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-03
      • 1970-01-01
      • 1970-01-01
      • 2021-05-17
      • 2020-05-18
      • 1970-01-01
      • 2020-02-05
      • 2020-09-28
      相关资源
      最近更新 更多