2017-05-29 69 views
2

我使用终极版做一个简单的商店,不幸的是它抛出这个错误:无法转换未定义或为空反对终极版

Cannot convert undefined or null to object 

浏览器指向进口终极版

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

回答

3

该错误是在减速机抛出您要的状态对象上流传一个不存在的属性

...state.polls, 

为了能够做到这一点,你必须确定你的初始状态的形状作为例子

const initialState = { 
    polls: [], 
}; 

完整的工作代码

import * as redux from "redux" 

const initialState = { 
    polls: [], 
}; 

let reducer = (state = initialState, 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 
    } 
})