我是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;
}
}
如果我改變這些行 const newTurn = Object.assign(state.currentTurn,action.data); return Object.assign(state,{currentTurn:newTurn}); 至此 返回狀態; 即使console.log高於這些語句,也會記錄state和action.data的正確值。到底是怎麼回事? :( –
一些代碼風格的建議:最好在'mapDispatchToProps'中有一箇中間函數,而不是組件中的方法:'const mapDispatchToProps =(dispatch)=>({rollDice:()=> dispatch(actions.rollDice )}});'。然後在組件中,你只需調用'this.props.rollDice()'。 – timotgl