【问题标题】:Redux state returns undefined after an updateRedux 状态在更新后返回 undefined
【发布时间】:2016-11-20 05:28:44
【问题描述】:

我有一个工作正常的简单减速器状态。 M减速机在下方。

const initialState  =
{
plan: [
    {
       id: 0,
       text: 'Submit math assignment at noon.',
       completed: false
    }
]
}
function mytodo(state = initialState, type) {
    switch(type) {
        ...
        default: 
            return state;    
    }
}

我的应用程序运行良好。然后将一些本地存储数据连接到我的状态。我的状态现在返回未定义。

const storageItems = JSON.parse(localStorage.getItem('plan'));

 function mytodo(state = initialState, type) {
        switch(type) {
            ...
            default: 
                console.log('the storage data is', storageItems);
                return storageItems ? state.plan.concat(storageItems) : state;    
        }
    }

我确认上面的存储项目有数据,但我的减速器将未定义的计划返回给我的组件。然后我将其更改为。

const storageItems = JSON.parse(localStorage.getItem('plan'));
if(storageItems) {
    initialState = initialState.todos.concat(storageItems);
    console.log('the states are', initialState);
}

function mytodo(state = initialState, type) {
        switch(type) {
            ...
            default: 
                return state;    
        }
    }

并将 initialState 更改为 let。它仍然返回未定义。上面控制台的初始状态返回我需要的完整结果。但是,如果我更新了 initialState,它不会将值返回给我的组件。请问我做错了什么?我该如何解决这个问题?任何帮助将不胜感激。

【问题讨论】:

    标签: javascript redux


    【解决方案1】:

    Array.prototype.concat() 返回一个新的数组对象 https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/concat 。检查引发错误的位置。该对象可能不为空,但顺序可能已更改。

    const initialState  =
    {
    plan: [
        {
           id: 0,
           text: 'Submit math assignment at noon.',
           completed: false
        }
    ]
    }
    

    从上面看,initialState.plan 应该返回你的计划数组。

    然而,

    initialState = initialState.todos.concat(storageItems);
    

    将返回新数组。现在您的 initialState 将采用以下形式

    initialState = [{
               id: 0,
               text: 'Submit math assignment at noon.',
               completed: false
            }]
    

    因此,如果您在任何地方都有 state.plan,则会抛出未定义的错误,因为您的状态已更改。希望在这里 concat https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/concat

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-12-11
      • 2018-09-28
      • 1970-01-01
      • 1970-01-01
      • 2017-01-24
      • 2017-12-08
      • 1970-01-01
      相关资源
      最近更新 更多