2016-10-26 29 views
1

現在我做我的減速器如下:如何最好地初始化狀態/設置第一狀態中反應,和/終極版

export default function (state = null, action) { 

    if(state==null) 
    { 
     state = [ 
      { 
       id: 1, 
       first: "Bucky", 
       last: "Roberts", 
       age: 71, 
       description: "Bucky is a React developer and YouTuber", 
       thumbnail: "http://i.imgur.com/7yUvePI.jpg" 
      }, 
      { 
       id: 2, 
       first: "Joby", 
       last: "Wasilenko", 
       age: 27, 
       description: "Joby loves the Packers, cheese, and turtles.", 
       thumbnail: "http://i.imgur.com/52xRlm8.png" 
      }, 
      { 
       id: 3, 
       first: "Madison", 
       last: "Williams", 
       age: 24, 
       description: "Madi likes her dog but it is really annoying.", 
       thumbnail: "http://i.imgur.com/4EMtxHB.png" 
      } 
     ] 
    } 

    switch (action.type) { 
     case 'USER_DELETED': 
      return state.filter(user => user.id !== action.userIdToDelete); 
    } 

    return state; 
} 

所以我檢查狀態是否爲空,如果是我填充它。有沒有更好的方法來做到這一點,即不從內部填充我的減速器?貌似不好的做法,我...

回答

1

而是爲它空默認值的 - 做以下

 initialState = [ 
     { 
      id: 1, 
      first: "Bucky", 
      last: "Roberts", 
      age: 71, 
      description: "Bucky is a React developer and YouTuber", 
      thumbnail: "http://i.imgur.com/7yUvePI.jpg" 
     }, 
     { 
      id: 2, 
      first: "Joby", 
      last: "Wasilenko", 
      age: 27, 
      description: "Joby loves the Packers, cheese, and turtles.", 
      thumbnail: "http://i.imgur.com/52xRlm8.png" 
     }, 
     { 
      id: 3, 
      first: "Madison", 
      last: "Williams", 
      age: 24, 
      description: "Madi likes her dog but it is really annoying.", 
      thumbnail: "http://i.imgur.com/4EMtxHB.png" 
     } 
    ]; 

    export default function (state = initalState, action) { 
    ... 
    } 
1

你應該始終設置爲默認狀態值,你期望它的類型是的,所以這裏function (state=[])比較好。將它設置爲空是一種反模式。

然後作爲默認初始狀態,你應該使用第二個參數中createStore設置初始狀態數據:http://redux.js.org/docs/api/createStore.html

+0

感謝。然而,我的第二個參數是'applyMiddleware(thunk,promise,logger)'這是不正確的呢? –

+1

當您包含初始(預加載)狀態時,您的應用中間件成爲您的第三個參數。 因此,在我發送createStore(reducer,[preloadedState],[enhancer])的鏈接中,增強器就是您的中間件。 – joejknowles

相關問題