reactjs - 更新深层结构中的状态而不重新渲染组件

标签 reactjs redux

我刚刚开始使用 React+Redux,但遇到了一个问题。 我知道我永远不应该改变 reducer 中的旧状态,而且我也没有这样做。

但是,当我在reducer中更改这样的变量时,即使我有带有state.coupons的mapStateToProps,我的组件也不会重新渲染

// this deep copies everything
let newState = Object.assign({}, state);

newState.coupons[2].events[0].eventRows[0].alternatives[0].selected = true;

return newState;

我做错了什么?

编辑: 我什至测试使用 newState = JSON.stringify(JSON.parse(oldState)) 但没有成功

编辑: 这是我的 mapStateToProps 函数

const mapStateToProps = (state, ownProps) => ({
  coupons: state.coupons,
  currentDraw: state.currentDraw
});

最佳答案

您可以在 redux 文档中找到解决方案:http://redux.js.org/docs/recipes/reducers/ImmutableUpdatePatterns.html#updating-nested-objects

The key to updating nested data is that every level of nesting must be copied and updated appropriately. This is often a difficult concept for those learning Redux, and there are some specific problems that frequently occur when trying to update nested objects. These lead to accidental direct mutation, and should be avoided.

您可以手动执行此操作,例如:

function updateVeryNestedField(state, action) {
    return {
        ....state,
        first : {
            ...state.first,
            second : {
                ...state.first.second,
                [action.someId] : {
                    ...state.first.second[action.someId],
                    fourth : action.someValue
                }
            }
        }
    }
}

实际上,最好使用辅助库来执行此操作。您可以在 https://github.com/markerikson/redux-ecosystem-links/blob/master/immutable-data.md#immutable-update-utilities 找到帮助程序库的列表。 ,我个人推荐immutability-helper或者只是切换到immutable.js .

关于reactjs - 更新深层结构中的状态而不重新渲染组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43844369/

相关文章:

javascript - 为什么 .map() 不返回任何内容?

javascript - React-Redux CSS 转换

reactjs - 以 redux-form 形式使用 axios 和 redux-thunk 发布请求

javascript - 渲染顺序中的 Thunk

javascript - React redux - 在Reducer中编写的api响应后如何获取各个组件中的数据

javascript - react-window fixedSizeGrid 与 react-window-infinite-loader

javascript - 在 react 组件中开 Jest 模拟异步调用

reactjs - ReduxForm : using formValueSelector within a FieldArray for conditional fields doesn't render immediately

javascript - FlatList 不会在 React-Native 中渲染任何文本

javascript - React js-显示状态值取决于 redux props 值