【问题标题】:Redux: Action is being called properly but reducer is not updating the state, just keeping the initial stateRedux:动作被正确调用但reducer没有更新状态,只是保持初始状态
【发布时间】:2020-02-09 23:40:26
【问题描述】:

我一直在使用 React、Redux、Redux-thunk 构建应用程序。 在调用 action 时,reducer 正确接收了有效负载和类型,但它没有修改它们。

  • 我的减速机:
import EditorActionTypes from './editor.types';

const INITIAL_STATE = {
    editorModified: false,
    tabs: [
        {
            name: 'main.js',
            active: true
        },
        {
            name: 'setup.js',
            active: false
        }
    ]
};

const editorReducer = ( state = INITIAL_STATE, action ) => {
    switch (action.payload) {
        case EditorActionTypes.SELECT_TAB:
            return {
                ...state,
                tabs: [
                    ...state.tabs.map( 
                        (tab, index) => index === action.payload
                            ? tab.active = true
                            : tab.active = false
                        )
                ]
            }

        default:
            return state;
    }
};

export default editorReducer;

【问题讨论】:

    标签: reactjs redux


    【解决方案1】:

    我认为有问题的部分是:

                     ...state.tabs.map( 
                            (tab, index) => index === action.payload
                                ? tab.active = true
                                : tab.active = false
                            )
    

    您没有从 map 内的函数返回任何内容。相反,您应该返回选项卡对象。

                     ...state.tabs.map( 
                            (tab, index) => ({ 
                               ...tab,
                               isActive: index === action.payload
                            }))
    

    正如@Gangadhar Gandi 指出的那样,您应该打开 action.type,而不是 action.payload

    【讨论】:

    • 也谢谢你。这是我在解决我的问题后注意到的下一个问题,认为 GangadharGandi 的答案。长夜错别字!完全是我的错。 :D
    【解决方案2】:

    开关条件错误, Reducer 函数应该检查 action.type

    switch (action.type) {
            case EditorActionTypes.SELECT_TAB:
                return {
    

    【讨论】:

      猜你喜欢
      • 2020-05-23
      • 1970-01-01
      • 1970-01-01
      • 2019-07-28
      • 1970-01-01
      • 2018-07-26
      • 1970-01-01
      • 2021-01-02
      • 2019-05-15
      相关资源
      最近更新 更多