在发货后立即使用更新的redux状态

时间:2016-12-21 12:38:57

标签: reactjs redux react-redux

我正在使用react-redux,并在我的redux状态中添加了一个'filters'字段,其中包含了我想用来从我的数据库接收数据的所有过滤器。

我的目标是在添加过滤器后立即使用更新过滤器从db接收数据。这是我到目前为止所得到的:

--- actions.js ---

...
    export function addFilter(filter, value) {
        return {
            type: 'ADD_FILTER',
            filter: filter,
            value: value
        }
    }
...

--- reducer.js ---

...
      case 'ADD_FILTER':
            return update(state, {
                filters: {
                    $merge: {
                        [action.filter]: action.value
                    }
                }
            });
...

--- filteringComponent.js ---

...
    addFilterAndUpdateData(filter, value) {
        this.props.addFilter(filter, value);
        this.props.getData(this.props.filters); 
        // this.props.filters is connected to state.filters.
        // it DOES update, but not right away. so when getData is dispatched
        // this.props.filters holds the old object and not the updated one
    }
...

添加过滤器后,我想立即调度getData操作,以便从db接收带有最新过滤器的数据。

问题是 this.props.filters尚未更新。 有没有办法“等待”更新?

到目前为止我提出的最佳解决方案是使用componentWillReceiveProps,但是我必须添加条件(因为我不一定要在每次更改道具时调度getData,只有当它是过滤器的结果时才会更新)

这里的'react-redux'方法是什么?

1 个答案:

答案 0 :(得分:1)

在这种情况下请求正确的react-redux方法,使用componentWillReceiveProps是正确的,在询问最佳做法时,我建议您阅读以下内容:

  1. redux-saga:它会处理您的异步操作并让其他人听一下(这是您的用例)

  2. ImmutableJs,只要它的任何值更改(在您的情况下为this.props.filters,它就会为您更改组件道具,因此它只会找到您更新的数据,如果它真的更新)

  3. React.PureComponent,可以使用此代替React.Component,如果有任何更改,它会通过深入检查props对象来提高渲染React组件的性能。

  4. 同样,如果您没有时间或灵活性来应用此项目,那么在componentWillReceiveProps中编写一些支票并没有错。

相关问题