简体   繁体   English

减速器未返回更新状态

[英]Reducer not returning updated state

I can't get my reducer to return updated state. 我无法让我的减速器返回更新状态。

The action (confirmed with debugger) is an array of objects - something like: [{name: "test"}, {name: "second_test"}] 该操作(已通过调试程序确认)是一个对象数组-类似于: [{name: "test"}, {name: "second_test"}]

I think something must be wrong with my spread operator, although I've also tried Object.assign() in the debugger and that seems to return the expected result. 我认为我的传播运算符肯定有问题,尽管我也在调试器中尝试了Object.assign() ,但这似乎返回了预期的结果。

My components is apparently just getting the default state. 我的组件显然只是处于默认状态。 Here's my reducer code. 这是我的减速器代码。 Any help would be appreciated. 任何帮助,将不胜感激。 Thank you! 谢谢!

const initialState = {
    current: {},
    all: []
}

export default function deckReducer(state = initialState, action) {
    switch(action.type) {
        case 'CREATE_DECK':
            return {...state, all: [...state.all, action.payload]}

        case 'FETCH_DECKS':

            debugger;
            return {...state, all: action.payload}

        default: return state
    }
}

I had this very issue recently (exactly as you describe), and I resolved the problem by using the immutability-helper package which is listed here on the ReactJS docs . 我最近( 恰如您所描述的)遇到了这个问题,并且我使用了ReactJS文档中列出的immutability immutability-helper包解决了这个问题。

This approach allows you to delegate the heavy lifting of state immutability and nested state updates. 这种方法使您可以委派繁重的状态不变性和嵌套状态更新。 You should find this resolves your issue: 您应该发现这可以解决您的问题:

import update from 'immutability-helper';

const initialState = {
    current: {},
    all: []
}

export default function deckReducer(state = initialState, action) {

    switch(action.type) {

        case 'CREATE_DECK': {
            /* Add payload to nested state.all list */
            return update(state, { all : { $push : [action.payload] }});
        }

        case 'FETCH_DECKS': {    
            /* Replace state.all with incoming payload */
            return update(state, { all : { $set : action.payload }});
        }

        default: return state
    }
}

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

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