【问题标题】:Setting State and performing new Searches in React在 React 中设置状态并执行新的搜索
【发布时间】:2017-04-24 21:22:55
【问题描述】:

我有这个 React 应用程序,它由 babel 编译并由 webpack 打包。

在时间表页面TimetableManagePage.js我有这个sn-p:

nextWeek() {
    this.setState({
        today: this.state.today.clone().add(1, 'w')
    });

    this.searchSessions();
}

previousWeek() {
    this.setState({
        today: this.state.today.clone().subtract(1, 'w')
    });

    this.searchSessions();
}

searchSessions() {
    this.props.actions.searchSessions({
            query: {
                range: {
                    when: {
                        gte: this.state.today.clone().startOf('week').toISOString(),
                        lte: this.state.today.clone().endOf('week').toISOString()
                    }
                }
            }
        })
        .then(() => this.setState({loading: false}))
        .catch(() => this.setState({loading: false}));
}

这个想法是,如果有人单击此箭头:

它将移至下一周或上一周。

searchSessions 运行 today 的状态,previousWeeknextWeek 更新。但是,我发现运行搜索时状态没有更新。

this.props.actions.searchSessions 更新一个 redux 存储状态,所以会在组件上设置新的 props...

现在,我想也许这个搜索实际上属于render函数,到那时所有状态都应该改变......但是,组件中的任何状态变化都会导致render重新运行,这意味着对搜索的调用可能会超过应有的负载。

当只更新今天的状态时,执行新搜索的最佳方式是什么?我应该看componentWillUpdate

【问题讨论】:

    标签: javascript reactjs redux-thunk


    【解决方案1】:

    你应该添加 shouldComponentUpdate(nextState) 函数并且应该比较

    shouldComponentUpdate(nextState){  
     if(nextState.today != this.state.today) 
       return true;
    }
    

    那么它只会在今天状态更新时更新您的页面。之后,您可以从 componentWillUpdate 或任何您想要的地方调用它。

    componentWillUpdate(nextState){
      if(nextState.today!=this.state.today){
         doIt();
       }
    }
    

    【讨论】:

    • today不是组件上的唯一状态,还有isSavingshowModalloading....
    • 在那里你将把你的代码添加到 componentWillUpdate(nextState) 中,如果(state.today is changed)做某事,同样的事情会再次发生......我只添加了它只运行一次。跨度>
    • 我正在使用componentDidUpdate,这样所有的状态更改都会执行,但完成后,我会检查today 是否更改并相应地运行搜索
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-19
    • 1970-01-01
    • 2017-08-17
    • 2017-05-30
    • 2017-07-18
    相关资源
    最近更新 更多