我是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