无法将undefined或null转换为对象redux

时间:2017-05-29 22:50:40

标签: javascript reactjs redux react-redux

我使用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
    }
})

1 个答案:

答案 0 :(得分:12)

在您的reducer中抛出该错误,您试图在状态对象上传播不存在的属性

...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
    }
})