redux dispatch不起作用

时间:2017-12-31 06:04:33

标签: redux dispatch

我是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())

这是我的错误enter image description here

1 个答案:

答案 0 :(得分:4)

问题在这一行,

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());