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

BaH*_*Jr. 7 javascript reactjs redux react-redux

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

 Cannot convert undefined or null to object
Run Code Online (Sandbox Code Playgroud)

浏览器指向导入Redux的行

import * as redux from "redux"
Run Code Online (Sandbox Code Playgroud)

我也尝试过这种方式导入它但它从"redux"给出了相同的错误import {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
    }
})
Run Code Online (Sandbox Code Playgroud)

Ste*_*n J 17

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

...state.polls,
Run Code Online (Sandbox Code Playgroud)

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

const initialState = {
    polls: [],
};
Run Code Online (Sandbox Code Playgroud)

您的示例的完整工作代码

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
    }
})
Run Code Online (Sandbox Code Playgroud)