【发布时间】:2018-09-03 13:16:34
【问题描述】:
作为练习,我正在编写一个 react-redux 计算器应用程序。我的应用状态定义为:
const initialState = {
operator1: "", //first operand
operator2: "", //second operand
currentOp: "", // +, -, *, /
display:"", //the current calculator display
currentOperator:1 //which operand is being entered right now
}
currentOp 保存计算器当前正在执行的操作的符号,当输入第一个操作数时,该符号为空。因此,当按下计算器的数字时,我需要更新显示,但不会丢失我的其他状态属性。我这样写了我的减速器:
import {NUMBER_PRESSED,OPERATION_PRESSED,EQUAL_PRESSED} from './actions';
const mainReducer = (state ={},action) =>
{
console.log("reducer called!");
console.log(action);
const newState = {};
//copy the operators to the new state. Only one will be changed. (Is this really necessary?)
newState.operator1 = state.operator1;
newState.operator2 = state.operator2;
switch(action.type)
{
case NUMBER_PRESSED:
if (state.currentOperator===1)
{
newState.operator1 = state.operator1 + action.payload;
newState.display= newState.operator1;
}
if(state.currentOperator===2)
{
newState.operator2 = state.operator2 + action.payload;
newState.display= newState.operator2;
}
//set the other properties of the state (Is this really necessary?)
newState.currentOperator = state.currentOperator;
newState.currentOp = state.currentOp;
console.log("The new state is:");
console.log(newState);
return newState;
case OPERATION_PRESSED:
break;
case EQUAL_PRESSED:
break;
default:
return state;
}
}
export default mainReducer;
请注意,我还没有实现计算操作,只是更新了显示。如果我直接更改状态变量,计算器组件不会更新。可以理解,这是文档中解释的预期行为。但是,似乎我需要手动将整个状态复制到一个新变量中,以便保留下一个状态(注意“这真的有必要吗?”代码中的 cmets。 我复制所有应用程序的状态并返回一个全新的状态对象没有问题,但是在具有巨大状态树的大型应用程序上会发生什么?这是如何管理的?有没有办法只修改redux中的部分状态?
【问题讨论】:
标签: reactjs redux react-redux