簡體   English   中英

如何使用反應鈎子從 redux state 中刪除項目

[英]How remove item from redux state using react hooks

我有一個部分,用戶可以使用更改輸入來更改數據,現在我希望能夠從 redux state 中刪除項目。

這里是代碼沙盒鏈接: live demo

減速器

const initialState = {
  firstName: "Kunta ",
  lastName: "Kinte",
  age: 35,
  country: "Ghana",
  IQ: 200
};

const DetailsReducer = (state = initialState, action) => {
  const { name, value } = action;

  return { ...state, [name]: value };
};

export default DetailsReducer;

這是我如何顯示數據並嘗試刪除名字但沒有任何反應

import { useSelector } from "react-redux";

const Details = () => {
  const details = useSelector((state) => state);

  const handleDelete = () => {
    details.firstName = "";
  };

  return (
    <div>
      <h1> Details </h1>
      <span> Firstname : {details.firstName}</span>
      <button onClick={handleDelete}>Delete</button>
      <br />
      <span> LastName : {details.lastName}</span>
      <button>Delete</button>
      <br />
      <span> age : {details.age}</span>
      <button>Delete</button>
      <br />
      <span> country : {details.country}</span>
      <button>Delete</button> <br />
    </div>
  );
};

export default Details;

像這樣從 redux state 中刪除項目的正確方法是什么?

要更改 redux state,我們需要使用 useDispatch 掛鈎。

在你的情況下:

import { useSelector, useDispatch } from "react-redux";

const Details = () => {
  const details = useSelector((state) => state);
  const dispatch = useDispatch();
  
  const handleDelete = () => {
    dispatch({
      type: "change",
      name: "firstName",
      value: "",
    });
  }

  ...

您可以在 reducer 中使用 type 屬性將各種行為添加到 redux state 管理中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM