2017-08-06 53 views
0

我是react.js的初學者。我正在做一個棋盤遊戲作爲初學者項目。有一個組件可以擲骰子。擲骰子時,會分派一個動作,以便更改狀態以反映擲骰子的值。但是在reducer中,state和action.data的值都是相同的。這怎麼可能?不知何故在減速機中獲得更新狀態

我有一個骰子滾動組件,它返回此:

當你點擊按鈕,一個行動派,這是由它添加骰子值應該更新的狀態。

rollDice(){ 
     console.log("this.props ||||| rollDice()", this.props); 
     if(this.props.isDiceRolled){ 
      alert("Move the marker..."); 
      return; 
     } 
     this.props.dispatch({ 
      type: "ROLL_DICE", 
      data: { 
       dice: Math.ceil(Math.random() * 5), 
       isDiceRolled: true 
      } 
     }); 
    } 

在減速:

switch(action.type){ 

    . 
    . 
    . 

    case "ROLL_DICE": { 
     console.log("ROLL_DICE"); 
     console.log(state, action.data); 
     const newTurn = Object.assign(state.currentTurn, action.data); 
     return Object.assign(state, { currentTurn: newTurn }); 
    } 
    default: { 
     return state; 
    } 

} 
+0

如果我改變這些行 const newTurn = Object.assign(state.currentTurn,action.data); return Object.assign(state,{currentTurn:newTurn}); 至此 返回狀態; 即使console.log高於這些語句,也會記錄state和action.data的正確值。到底是怎麼回事? :( –

+1

一些代碼風格的建議:最好在'mapDispatchToProps'中有一箇中間函數,而不是組件中的方法:'const mapDispatchToProps =(dispatch)=>({rollDice:()=> dispatch(actions.rollDice )}});'。然後在組件中,你只需調用'this.props.rollDice()'。 – timotgl

回答

4

隨着終極版,在減速,每次都返回一個新的狀態的時間。 因此,而不是兩行:

const newTurn = Object.assign(state.currentTurn, action.data); 
return Object.assign(state, { currentTurn: newTurn }); 

你應該寫這樣的事情

const newTurn = Object.assign({}, state.currentTurn, action.data); 
return Object.assign(
    {}, 
    state, 
    { currentTurn: newTurn} 
) 

問題應與Object.assign。在這裏閱讀更多:https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

+0

OMG我做了什麼?!我想Object.assign錯了 - 以爲它是純的。謝謝... –

+0

沒有概率!只要Object.assign合併第一個參數的所有屬性並返回該屬性,但如果嘗試手動更新其狀態,則redux不會很高興 – maxgallo