redux 调度不起作用

redux dispatch does not work

我是 redux 初学者,现在一切都让我感到困惑。我正在尝试创建一个商店并向商店发送一个新值,但它不起作用,有人可以帮忙吗?谢谢

import {createStore, combineReducers} from 'redux';
import uuid from 'uuid';

const state={
    id:0,
    numbers:[]
}

const randomNumber=()=>{...}

//reducer

const reducer=(state={},action)=>{
    switch(action.type){
        case 'ADD_NUMBER':
        const newNumber={id:state.id+1, number:randomNumber()}
        return {
            ...state,
            id:uuid(),
            numbers:[...state.numbers,newNumber]
        }
    }
}

//store
const store=createStore(reducer)
store.subscribe(()=>{const state=store.getState})
console.log('new state should update, but it does not: ', state)

const addNumber =()=>({type: 'ADD_NUMBER'})

//dispatch
store.dispatch(addNumber())

这是我的错误

问题出在这一行,

const reducer = (state = {}, action) => {

请注意,您已将状态初始化为空对象 {}。因此,当您尝试传播 state.numbers 时,您会收到此错误,因为 numbers 未在初始状态下定义。

return {
   ...state,
   id:uuid(),
   numbers:[...state.numbers,newNumber]
}

重现您的问题的最小示例,

const bad = (state = {}) => {
  return {
    numbers:[...state.numbers]
  }
}

bad();

要解决此问题,您需要使用默认值初始化您的状态,

const INITIAL_STATE = {
    id:0,
    numbers:[]
}


//reducer
const reducer = (state = INITIAL_STATE, action) => {

// Rest of the code

const INITIAL_STATE = {
    id:0,
    numbers:[]
}
 
const good = (state = INITIAL_STATE) => {
  return {
    numbers:[...state.numbers]
  }
}

console.log(good());