2017-05-29 67 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 
    } 
}) 
相關問題