簡體   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