【问题标题】:Not getting updated state from redux store when the state is update状态更新时未从 redux 存储中获取更新状态
【发布时间】:2020-06-10 12:37:03
【问题描述】:

当我更新计数器 1 时,它会增加,但组件没有获得更新的状态。状态更新后,计数器未显示更新的数字。但是,如果我转到另一个组件并返回计数器组件,那么我会得到更新的状态。这是柜台页面-

 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);

当从组件调用“increaseXaomi”方法时会调用计数器操作。

export function increaseXaomi(num=1){
    return (dispatch)=>{
        dispatch({
            type:'INCREASE_XAOMI',
            payload:num
        })
    }
}

Counter Reducer 获取增加计数器的动作类型和计数器值。它返回更新的状态。

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;

【问题讨论】:

    标签: javascript reactjs redux react-redux


    【解决方案1】:

    你正在改变 reducer 的状态。

    您应该始终返回您的状态的新实例。

    function counterReducer(state=initState,action){
       switch(action.type){
          case 'INCREASE_XAOMI':
              return { ...state, xaomi: state.xaomi + action.payload };
          default:
              return state;
       }
    }
    

    【讨论】:

    • 我有一个对象数组,我想从中删除一个项目,但它不会实时重新更新商店也许我做错了,我只是让一个函数助手处理这种情况但是可能效果不好,here
    【解决方案2】:

    当你使用 redux 时,你想确保你没有改变状态,你需要创建一个新的状态对象(浅拷贝)。 有关 redux 中的突变和更新模式的更多信息,请参阅此 link

    你的代码应该是:

    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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-30
      • 2018-08-04
      • 1970-01-01
      相关资源
      最近更新 更多