简体   繁体   English

如何根据我的初始 state 更新 state

[英]How to update the state based on my initial state

What I'm trying to do here is to build a dynamic component, that will be responsible to take an array of objects and the form will be built based on my formState.我在这里要做的是构建一个动态组件,它将负责获取一组对象,并且表单将基于我的 formState 构建。 So I made my initial State and used.map to make the loop over the state and mapped the keys to making the label, value, and inputs appear based on the state. but my problem is at onChange.所以我制作了我的初始 State 并使用 .map 在 state 上进行循环并将键映射到使 label、值和输入基于 state 出现。但我的问题是在 onChange 上。 How to update the value key in every object and set the new state for it.如何更新每个 object 中的值键并为其设置新的 state。 any advice, please.任何建议,请。

import { useState } from "react";
import InputText from "./components";
import useForm from "./hooks/useForm";

function App() {
  interface formStateT {
    id: number;
    label: string;
    value: any;
    error: string;
  }

  const formState = [
    {
      id: 0,
      label: "firstName",
      value: "",
      error: "",
    },
    {
      id: 1,
      label: "lastName",
      value: "",
      error: "",
    },
  ];

  const { form, validate, setForm, checkValidHandler } = useForm(formState);
  const [error, setError] = useState("");

  const submitFormHandler = (e: { preventDefault: () => void }) => {
    e.preventDefault();

    checkValidHandler();

    // write form logic
    // setError() will be used to take the error message

    console.log(form);
  };

  return (
    <form onSubmit={(e) => submitFormHandler(e)}>
      {form.map((f: formStateT) => (
        <InputText
          key={f.id}
          label={f.label}
          value={f.value}
          onChange={(e) => {
            // Im trying here to update the value key of every label key.
            // setForm({ ...form, [f.label.valueOf()]: f.value })
          }}
          valid={f.value === "" ? validate.notValid : validate.valid}
          errorMsg={error === "" ? f.error : error}
          classes={"class"}
        />
      ))}
      <button>Submit</button>
    </form>
  );
}

export default App;

From your comment, f.value = e.target.value;根据您的评论, f.value = e.target.value; is a state mutation and should be avoided, the setForm([...form]);是一个 state 突变,应该避免, setForm([...form]); is masking the mutation.正在掩盖突变。

In App create an onChangeHandler function that takes the onChange event object and the index you want to update.App中创建一个onChangeHandler function,它接受onChange事件 object 和您要更新的索引。 Unpack the value from the onChange event and update the state. The handler should use a functional state update to update from the previous state, and create a shallow copy of the form array, using the index to shallow copy and update the correct array element.onChange事件中解压value并更新 state。处理程序应使用功能性 state 更新来更新之前的 state,并创建form数组的浅表副本,使用索引浅表复制并更新正确的数组元素。

Example:例子:

// curried function to close over index in scope, and
// return handler function to consume event object
const onChangeHandler = index => e => {
  const { value } = e.target;
  setForm(form => form.map((el, i) => 
    i === index
      ? { ...el, value }
      : el
  ));
};

...

<form onSubmit={submitFormHandler}>
  {form.map((f: formStateT, index: number) => (
    <InputText
      key={f.id}
      label={f.label}
      value={f.value}
      onChange={onChangeHandler(index)} // <-- invoke and pass mapped index
      valid={f.value === "" ? validate.notValid : validate.valid}
      errorMsg={error === "" ? f.error : error}
      classes={"class"}
    />
  ))}
  <button>Submit</button>
</form>

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

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