繁体   English   中英

如何通过单击按钮从反应组件修改 redux 变量 state?

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

我从事 react-redux 项目已经有一段时间了。 在 redux 我有一个 id 变量,初始 state 为0 我希望在单击按钮时更改此值。 为此,我有两个按钮button1button2 当我单击button1时,我想在单击button2时将id state 更改为12

这是我的代码。

idReducer.js

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

动作.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 组件用两个按钮来改变id的 state

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;

问题:单击button1时,我想在单击button2时将id的state更改为12

谢谢。

您需要修改减速器以实际使用paylad:


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

让您的操作将 id 作为有效负载传递(我会考虑使用更好的东西作为操作名称而不是id ):

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

然后使用具有此 ID 的调度调用您的操作 onclick

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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