我正在为一个简单的计算器编写react-redux代码。这是我的组件文件
import React from 'react';
import {connect} from 'react-redux';
class Calculator extends React.Component{
render(){
return(
<div className="text-center">
<div>
<div>
<button name='1' value='1' onClick={()=>this.props.addition('1')}>1</button>
<button name='2' value='2' onClick={()=>this.props.addition('2')}>2</button>
<button name='3' value='3' onClick={()=>this.props.addition('3')}>3</button>
</div>
<div>
<button name='4' value='4' onClick={()=>this.props.addition('4')}>4</button>
<button name='5' value='5' onClick={()=>this.props.addition('5')}>5</button>
<button name='6' value='6' onClick={()=>this.props.addition('6')}>6</button>
</div>
<div>
<button name='7' value='7' onClick={()=>this.props.addition('7')}>7</button>
<button name='8' value='8' onClick={()=>this.props.addition('8')}>8</button>
<button name='9' value='9' onClick={()=>this.props.addition('9')}>9</button>
</div>
<div>
<button name='+' value='+' onClick={()=>this.props.addition('+')}>+</button>
<button name='0' value='0' onClick={()=>this.props.addition('0')}>0</button>
<button name='-' value='-' onClick={()=>this.props.addition('-')}>-</button>
</div>
<div>
<button name='/' value='/' onClick={()=>this.props.addition('/')}>/</button>
<button name='evalu' value='evalu' onClick={()=>this.props.evaluation('=')}>=</button>
<button name='*' value='*' onClick={()=>this.props.addition('*')}>*</button>
</div>
<div>
<button name='cler' value='cler' onClick={()=>this.props.addition('clear')}>clear</button>
<button name='bs' value='bs' onClick={()=>this.props.addition('bs')}>del</button>
</div>
</div>
</div>
)
}
}
const matchStatestoProps = state =>{
return {expression:state.expression}
}
const matchDispatchtoProps = dispatch =>{
return {
addition: (data)=> dispatch({type:'ADD',payload:data}),
evaluation: ()=>dispatch({type:'EVAL'})
}
}
export default connect(matchStatestoProps,matchDispatchtoProps)(Calculator);
这是我的减速器:
const defaultState={
expression:''
};
var rootReducer = (state=defaultState, {action,payload}) =>{
switch (action){
case 'ADD':
return {expression:state.expression+payload};
default: return defaultState;
}
}
export default rootReducer;
现在,当我单击按钮时,它会触发一个动作,但是状态没有得到更新。它仍然是空的。有人可以帮我吗?
这是redux商店的屏幕截图:
答案 0 :(得分:2)
您要通过键type
而不是键action
传递操作,因此不要像这样破坏参数:
var rootReducer = (state = defaultState, { action, payload }) =>{
您应该这样做
var rootReducer = (state = defaultState, { type, payload }) =>{
然后切换type
而不是action
。
答案 1 :(得分:1)
您需要从操作对象中获取文字
var rootReducer = (state=defaultState,{type, payload}) =>{
switch (type){
case 'ADD':
return {expression:state.expression+payload};
default: return defaultState;
}
}