[英]Not getting updated state from redux store when the state is update
When I update counter 1 it increases but the component is not getting the updated state.当我更新计数器 1 时,它会增加但组件没有获得更新的状态。 After the state is updated the counter didn't show updated number.
状态更新后,计数器没有显示更新的数字。 But if I go to another component and back to the counter component then I get the updated state.
但是,如果我转到另一个组件并返回到计数器组件,那么我将获得更新的状态。 Here is the counter page-
这是柜台页面-
import React, { Component } from 'react'
import {connect} from 'react-redux'
import {increaseXaomi} from '../../store/actions/counterAction';
class Counter extends Component {
increaseXaomi = ()=>{
this.props.increaseXaomi();
}
render() {
console.log(this.props)
return (
<div className="container">
<div className="row">
<p>Xaomi <strong>{this.props.xaomi}</strong></p>
<p>Iphone <strong>{this.props.iphone}</strong></p>
<p>Huai <strong>{this.props.huai}</strong></p>
<button className="btn" onClick={this.increaseXaomi}>Increase Xaomi</button>
</div>
</div>
)
}
}
const mapStateToProps = ({counter})=>{
return counter;
}
const mapDispatchToProps = (dispatch)=>{
return {
increaseXaomi: ()=>{
increaseXaomi(1)(dispatch)
}
}
}
export default connect(mapStateToProps,mapDispatchToProps)(Counter);
Counter action is called when the "increaseXaomi" method is called from the component.当从组件调用“increaseXaomi”方法时,会调用计数器操作。
export function increaseXaomi(num=1){
return (dispatch)=>{
dispatch({
type:'INCREASE_XAOMI',
payload:num
})
}
}
Counter Reducer get the action type and counter value for increasing the counter. Counter Reducer 获取增加计数器的动作类型和计数器值。 It return updated state.
它返回更新的状态。
let initState = {
xaomi:0,
iphone:0,
huai:0
}
function counterReducer(state=initState,action){
switch(action.type){
case 'INCREASE_XAOMI':
state.xaomi+=action.payload
return state;
default:
return state;
}
}
export default counterReducer;
When you are using redux you want to make sure you are not mutating the state, you need to create a new state object (a shallow copy).当你使用 redux 时,你想确保你没有改变状态,你需要创建一个新的状态对象(浅拷贝)。 Refer to this link for more info on mutations and update patterns in redux.
有关 redux 中突变和更新模式的更多信息,请参阅此链接。
Your code should be:你的代码应该是:
let initState = {
xaomi:0,
iphone:0,
huai:0
}
function counterReducer(state=initState,action){
switch(action.type){
case 'INCREASE_XAOMI':
return { ...state, xaomi: state.xaomi + action.payload };
default:
return state;
}
}
export default counterReducer;
You are mutating the state on the reducer.您正在改变减速器上的状态。
You should always return a new instance of your state.您应该始终返回状态的新实例。
function counterReducer(state=initState,action){
switch(action.type){
case 'INCREASE_XAOMI':
return { ...state, xaomi: state.xaomi + action.payload };
default:
return state;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.