【问题标题】:Cannot convert undefined or null to object redux无法将 undefined 或 null 转换为对象 redux
【发布时间】:2017-05-29 22:50:40
【问题描述】:

我正在使用 Redux 制作一个简单的商店,不幸的是它抛出了这个错误:

 Cannot convert undefined or null to object

浏览器指向导入Redux的那一行

import * as redux from "redux"

我也尝试过以这种方式导入它,但它给出了同样的错误 从“redux”导入 { createStore }

这是代码:

import * as redux from "redux"

let reducer = (state ={}, action) =>{
    switch(action.type) {
        case "ADD_POLL":
            return {
                polls: [
                    ...state.polls,
                    action.poll
                ]
            }
        default:
            return state
    }
}

let store = redux.createStore(reducer)

store.subscribe(()=>{
    let currentState = store.getState()
    console.log(currentState)
})

store.dispatch({
    type: "ADD_POLL",
    poll: {
        id: 1,
        title: "What's  your fav Color",
        votes: 230
    }
})

【问题讨论】:

    标签: javascript reactjs redux react-redux


    【解决方案1】:

    该错误被抛出,因为在你的减速器中你试图在状态对象上传播一个不存在的属性

    ...state.polls,
    

    为此,您必须将初始状态的形状定义为

    const initialState = {
        polls: [],
    };
    

    您的示例的完整工作代码

    import * as redux from "redux"
    
    const initialState = {
        polls: [],
    };
    
    const reducer = (state = initialState, action) =>{
        switch(action.type) {
            case "ADD_POLL":
                return {
                    polls: [
                        ...state.polls,
                        action.poll
                    ]
                }
            default:
                return state
        }
    }
    
    const store = redux.createStore(reducer)
    
    store.subscribe(()=>{
        let currentState = store.getState()
        console.log(currentState)
    })
    
    store.dispatch({
        type: "ADD_POLL",
        poll: {
            id: 1,
            title: "What's  your fav Color",
            votes: 230
        }
    })
    

    【讨论】:

      猜你喜欢
      • 2021-07-29
      • 2020-07-19
      • 2020-12-06
      • 1970-01-01
      • 2022-06-22
      • 2023-02-06
      • 2021-12-07
      • 2020-08-15
      • 1970-01-01
      相关资源
      最近更新 更多