2017-08-06 36 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