调度后立即使用更新的 redux 状态

Using updated redux state right after dispatch

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

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

--- 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 操作,以便从数据库接收具有最新过滤器的数据。

问题是this.props.filters还没有更新。 有没有办法'wait'进行更新?

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

此处正确的 'react-redux' 方法是什么?

为这种情况寻求正确的 react-redux 方法,使用 componentWillReceiveProps 是正确的,在寻求最佳实践的同时,我建议您阅读以下内容:

  1. redux-saga:它将处理您的异步操作并让一个人监听另一个人(这是您的用例)

  2. ImmutableJs,只要它的任何值发生变化(在你的情况下是this.props.filters,它就会为你处理改变你的组件道具,所以如果它真的更新了,它只会给你更新的数据)

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

同样,如果您没有时间或没有灵活性在您的项目中应用它,在 componentWillReceiveProps 中写一些检查并没有错。