简体   繁体   English

不确定如何正确更新Redux中的状态

[英]Not sure how to update State in Redux properly

I am not sure how to update the state properly in redux . 我不确定如何在redux正确更新state I get duplicated entries. 我得到重复的条目。

Thats how the state looks like 那就是state样子

const STATE = {
    windowOne: { ... }
    windwoTwo: { ... }
    windowThree: { ... }
}

That is one of my reducers 那是我的减速器之一

export default function reducer(state = STATE, action) {
    switch (action.type) {
        case type.WINDOW_ONE: {
            return {
                ...state,
                windowOne: {
                    ...state.windowOne,
                    foo: action.bar,
                }
            }
        }
    }
}

I map the state like to the props of my component 我将状态映射到组件的道具

function mapDispatchToProps(dispatch) {
    return bindActionCreators(combinedActions, dispatch);
}

const mapStateToProps = state => {
    const { windowOne } = state.windowOne;

    return {
        windowOne,
    };
}

export default connect(mapStateToProps, mapDispatchToProps)(SomeComponent);

And I combine the various reducers here 我在这里结合了各种异径管

export default combineReducers({
    windowOne,
    windowTwo,
    windowThree
});

When I use redux-logger , I see that in windowOne the whole state is copied. 当我使用redux-logger ,我看到在windowOne中整个state被复制了。 In there, after triggering an action , I find windowTwo and windowThree . 在其中,触发action ,我找到windowTwowindowThree I am also not sure why I have to specify windowOne in these lines 我也不确定为什么我必须在这些行中指定windowOne

    const { windowOne } = state.windowOne;

Shouldn't const { windowOne } = state be enough? const { windowOne } = state应该不够吗? That might be related... 那可能是相关的...

Check the docs for combineReducers ; 检查文档是否有combineReducers ; it takes care of sending to each reducer the appropriate slice of the state and merging the results. 它负责将适当的状态片发送给每个reducer并合并结果。 For the reducer shown, this means you should pass it the initial state for windowOne only and return just the updated state for windowOne : 对于所示的减速,这意味着你应该通过它的初始状态windowOne只和返回刚刚更新的状态windowOne

export default function reducer(state = STATE.windowOne, action) {
    switch (action.type) {
        case type.WINDOW_ONE: {
            return {
                ...state,
                foo: action.bar,
            }
        }
    }
}

After this, const { windowOne } = state in mapStateToProps should work. 在此之后, const { windowOne } = statemapStateToProps应该工作。 Also note that you'll need a default case in each reducer, as all reducers receive all actions, and that STATE might be more appropriately named initialState . 还要注意,在每个化简器中都需要一个默认的大小写,因为所有化简器都会接收所有操作,并且STATE可能更合适地命名为initialState

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM