【问题标题】:Using updated redux state right after dispatch [duplicate]在调度后立即使用更新的 redux 状态 [重复]
【发布时间】:2017-05-06 21:22:59
【问题描述】:

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

我的目标是在添加过滤器后立即使用更新的过滤器从 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
                    }
                }
            });
...

--- 过滤组件.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 尚未更新。 有没有办法“等待”更新?

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

这里正确的“react-redux”方法是什么?

【问题讨论】:

    标签: reactjs redux react-redux


    【解决方案1】:

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

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

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

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

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

    【讨论】:

      猜你喜欢
      • 2019-11-15
      • 1970-01-01
      • 2021-11-07
      • 1970-01-01
      • 2018-10-28
      • 2021-08-30
      • 2020-05-12
      • 2019-12-04
      • 2018-08-12
      相关资源
      最近更新 更多