【问题标题】:How to update a state entry in react and display it's contents in input field before updating?如何在更新前更新反应中的状态条目并在输入字段中显示其内容?
【发布时间】:2021-08-25 15:29:08
【问题描述】:

我正在创建一个可用于添加/更新/删除用户信息的购物车表单。我使用 react-hook-form 进行表单提交和验证。我的初始状态是空数组。添加用户时,对象会附加到状态数组中,例如 -

state = [
  { name: 'abc', age: '23' },
  { name: 'katy', age: '12' },
];

如果 div 行有一个编辑按钮并将其显示在现有输入框中,并且当我单击更新(另一个按钮)时,它如何更新状态值。

注意-名称可以相同,因此我不能使用 state.find()。

【问题讨论】:

  • 你可以为每个状态项使用id吗?
  • 在使用 react-hook-form 时,请浏览表单数组相关的钩子、函数。这也将提供唯一的 ID。
  • 如果您列出用户,您可以传递一个可能来自地图功能的 ID 并使用它来更改状态
  • @iunfixit,我在状态中没有 id,但有来自 map 函数的索引

标签: reactjs react-hook-form


【解决方案1】:

一种方法

const UpdateComponent = ({ id, user, setState }) => {
  const [userData, setUserData] = React.useState({
    id: 0,
    name: "",
    age: 0
  });

  React.useEffect(() => {
    setUserData({ id: id, name: user.name, age: user.age });
  }, [user, id]);

  const onChange = (e) => {
    setUserData((currentData) => ({
      ...currentData,
      [e.target.name]: e.target.value
    }));
  };

  const onSubmit = () => {
    setState((currentState) =>
      currentState.map((u) => (u.id === id ? userData : u))
    );
  };

  return (
    <>
      <input
        onChange={onChange}
        name="name"
        value={userData.name}
        placeholder="Name"
      />
      <input
        onChange={onChange}
        name="age"
        value={userData.age}
        placeholder="Age"
      />
      <button onClick={onSubmit} type="button">
        Update
      </button>
    </>
  );
};

const List = () => {
  const [state, setState] = React.useState([]);

  React.useEffect(() => {
    setState(
      [
        { name: "abc", age: "23" },
        { name: "katy", age: "12" }
      ].map((u, i) => ({ ...u, id: i }))
    );
  }, []);

  React.useEffect(() => {
    // debug
    console.log(state);
  }, [state]);

  return (
    <div>
      {state.map((user) => (
          <UpdateComponent
            key={user.id}
            id={user.id}
            user={user}
            setState={setState}
          />
        ))}
    </div>
  );
};

看看https://codesandbox.io/s/fragrant-surf-p5cxh?file=/src/App.js

您可以使用 UUID 包来生成 ID:

React.useEffect(() => {
// Generates IDs when loading the data as example
// but ideally IDs are created on user creation
setState(
  [
    { name: "abc", age: "23" },
    { name: "katy", age: "12" }
  ].map((u) => ({ ...u, id: uuidv4() }))
);
  }, []);

沙盒:https://codesandbox.io/s/unruffled-hypatia-tjzcx

但这与使用地图索引 id(在组件挂载上)的初始方法没有太大区别,这并不理想,因为我们在组件挂载时生成 ID,但至少它们不会在每个组件上不断变化渲染

我的初始状态是空数组。添加用户时,对象会附加到状态数组中,如

对于您的情况,您可以只拥有一个每次添加用户时递增的 ID,或者在添加时使用 uuid,因此您的数据已经带有 ID

【讨论】:

    猜你喜欢
    • 2020-12-26
    • 2022-01-08
    • 1970-01-01
    • 2021-10-09
    • 1970-01-01
    • 2020-06-16
    • 1970-01-01
    • 2021-11-27
    • 1970-01-01
    相关资源
    最近更新 更多