首页 > 解决方案 > 如何在反应原生的一个redux中添加多个计数器

问题描述

我想添加多个计数器,例如 countA、countV、countR,并希望在 onPress 上更新特定计数器。但是当我更新其中任何一个时。然后所有计数器更新。

这是我在 App.js 中尝试过的


const initialState={
  countA:0,
  countV:0,
  countR:0,

};



function reducer(state = initialState, action){
  switch(action.type){
    case "INCREMENTA":
      return {
        countA: state.countA + 1,
      }
      case "INCREMENTV":
      return {
        countV: state.countV + 1,
      }
      case "INCREMENTR":
      return {
        countR: state.countR+ 1,
      }
      default:
        return state;

  }
}

const store = createStore(reducer);

在 screen.js 中

incrementA = () => {
     this.props.dispatch({type:"INCREMENTA"})
    }

    incrementV = () => {
      this.props.dispatch({type:"INCREMENTV"})
     }

     incrementR = () => {
      this.props.dispatch({type:"INCREMENTR"})
     }

///here is onPress button



const mapStateToProps=(state)=>({
  countA:state.countA,
  countV:state.countV,
  countR:state.countR
})


export default connect(mapStateToProps)(detailScreen);

请忽略它 = 我想添加多个计数器,如 countA、countV、countR 并想更新 onPress 上的特定计数器。但是当我更新其中任何一个时。然后所有计数器更新。我想添加多个计数器,例如 countA、countV、countR,并希望在 onPress 上更新特定计数器。但是当我更新其中任何一个时。然后所有计数器更新。

标签: javascriptreact-nativereduxreact-redux

解决方案


在 Redux reducer 中,你必须返回全新的状态,所以你的代码应该是:

const initialState={
  countA:0,
  countV:0,
  countR:0,

};

function reducer(state = initialState, action){
  switch(action.type){
    case "INCREMENTA":
      return {
        ...state,
        countA: state.countA + 1,
      }
      case "INCREMENTV":
      return {
        ...state,
        countV: state.countV + 1,
      }
      case "INCREMENTR":
      return {
        ...state,
        countR: state.countR+ 1,
      }
      default:
        return state;
  }
}

const store = createStore(reducer);

推荐阅读