简体   繁体   中英

How to modify a redux variable state from react component with a button click?

I am working on react-redux project for quite sometime now. In redux I have an id variable with initial state of 0 . I want this value to be changed on button click. For this to happen, I have two buttons, button1 and button2 . when I click on button1 I wanted to change the id state to 1 and 2 when I click on button2 .

Here is my code.

idReducer.js

const processReducer = (state = 0, action) => {
  switch (action.type) {
    case "ID":
      return state;
    default:
      return state;
  }
};
export { processReducer };

action.js

export const id = () => {
  return {
    type: "ID",
  };
};

reducerAll.js

import { combineReducers } from "redux";
import { tokenReducer } from "./tokenReducer";
import { userDataReducer } from "./userReducer";
import { userStatusReducer } from "./userStatusReducer";
import { assetRiskReducer } from "./assetRiskReducer";
import { cpeReducer } from "./cpeReducer";
import { processReducer } from "./processReducer";

export default combineReducers({
  token: tokenReducer,
  user: userDataReducer,
  user_status: userStatusReducer,
  assetRisk: assetRiskReducer,
  id: processReducer,//MY ID REDUCER
});

ChangeState.js components with two buttons to change the state of id

import React from "react";
import { useDispatch, useSelector } from "react-redux";
import { id } from "./../../../auth/store/actions/index";
const ChangeState = () => {
  const id = useSelector((state) => state.id); //initial state of id=0
  const dispatch = useDispatch();
  return (
    <div>
      <button onClick={}>button1</button>
      <button onClick={}>button2</button>
    </div>
  );
};

export default ChangeState;

Problem: When button1 clicked, I want to change the state of id to 1 and 2 when button2 clicked.

Thanks.

You need to modify your reducer to actualy do something with paylad:


const processReducer = (state = 0, action) => {
  switch (action.type) {
    case "ID":
      return action.payload;
    default:
      return state;
  }
};
export { processReducer };

make your action to pass id as payload (i would consider to use something better as name of action instead of id ):

export const id = (id) => {
  return {
    type: "ID",
    payload: id,
  };
};

and then call your action onclick using dispatch with this ID

const ChangeState = () => {
  const id = useSelector((state) => state.id); //initial state of id=0
  const dispatch = useDispatch();
  return (
    <div>
      <button onClick={()=>dispatch(id(1))}>button1</button>
      <button onClick={()=>dispatch(id(1))}>button2</button>
    </div>
  );
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM