简体   繁体   English

为什么在 React 中更改 state 时我的子组件不更新数据?

[英]Why isn't my child component updating data when changing the state in React?

I have a list of users and I want to display in another component on the same page the user data in input fields for every user that I click on.我有一个用户列表,我想在同一页面的另一个组件中显示我单击的每个用户的输入字段中的用户数据。

When no user is selected, I want the component to just render some text and a button to add a user.当没有选择用户时,我希望组件只呈现一些文本和一个按钮来添加用户。 When the button is clicked the component renders the form with empty input fields so that we can add a new user.单击按钮时,组件会呈现带有空输入字段的表单,以便我们可以添加新用户。

I tried the following, but it's just showing the data for the first one I click on.我尝试了以下操作,但它只是显示我点击的第一个数据。 It's not updating.它没有更新。

The main page:主页:

const index = (props) => {
  const [selectedUser, setSelectedUser] = useState(null);
  const [state, setState] = useState("Index");

  const onChange = (item) => {
    setState("Edit");
    setSelectedUser(item);
  };

  const onClick = (e, item) => {
    if (e.type === "click" && e.clientX !== 0 && e.clientY !== 0) {
      onChange(item);
    } else {
      console.log('prevented "onClick" on keypress');
    }
  };

  const renderComponent = () => {
    switch (state) {
      case "Index":
        return (
          <>
            <div className="btn" onClick={(e) => setState("Edit")}>
              + New Staff
            </div>
            <img src="/storage/illustrations/collaboration.svg" />
          </>
        );
      case "Edit":
        return (
          <div>
            <StaffForm profile={selectedUser} />
          </div>
        );
    }
  };

  return (
    <>
      <div>
        <div>
          <h1>Staff</h1>
        </div>

        <div>
          <div>
            {profiles.map((item, index) => {
              return (
                <div key={index} onClick={(e) => onClick(e, item)}>
                  <input
                    type={"radio"}
                    name={"staff"}
                    checked={state === item}
                    onChange={(e) => onChange(item)}
                  />

                  <span>{item.user.name}</span>
                </div>
              );
            })}
          </div>
          <div>{renderComponent()}</div>
        </div>
      </div>
    </>
  );
};

The Staff Form Component:员工表单组件:

const StaffForm = ({ profile }) => {
  const { data, setData, post, processing, errors, reset } = useForm({
    email: profile ? profile.user.email : "",
    name: profile ? profile.user.name : "",
    phone_number: profile ? profile.user.phone_number : "",
    avatar: profile ? profile.user.avatar : "",
  });
  const [file, setFile] = useState(data.avatar);
  const handleImageUpload = (e) => {
    setFile(URL.createObjectURL(e.target.files[0]));
    setData("avatar", e.target.files[0]);
  };
  const onHandleChange = (event) => {
    setData(
      event.target.name,
      event.target.type === "checkbox"
        ? event.target.checked
        : event.target.value
    );
  };

  return (
    <div>
      <ImageUpload
        name={data.name}
        file={file}
        handleImageUpload={handleImageUpload}
      />
      <TextInput
        type="text"
        name="name"
        value={data.name}
        autoComplete="name"
        isFocused={true}
        onChange={onHandleChange}
        placeholder={t("Name")}
        required
      />
      <TextInput
        type="text"
        name="phone_number"
        value={data.phone_number}
        autoComplete="phone_number"
        placeholder={t("Phone Number")}
        onChange={onHandleChange}
        required
      />
      <TextInput
        type="email"
        name="email"
        value={data.email}
        autoComplete="email"
        onChange={onHandleChange}
        placeholder={t("Email")}
        required
      />
    </div>
  );
};
  1. First of all something you should avoid is the renderComponent() call.Check here the first mistake mentioned in this video .首先,您应该避免的是 renderComponent() 调用。在此处查看本视频中提到的第一个错误 This will most likely fix your problem but even if it doesn't the video explains why it should not be used.这很可能会解决您的问题,但即使不能,视频也解释了为什么不应使用它。
  2. Something else that caught my eye(possibly unrelated to your question but good to know) is the onChange function. When two pieces of state change together it is a potential source of problems, check out this article on when to use the useReducer hook . onChange function 引起了我的注意(可能与您的问题无关,但很高兴知道)。当两个 state 一起更改时,这是潜在的问题来源,请查看这篇关于何时使用 useReducer 钩子的文章
  3. Also be careful with naming React Components, they need to be capital case, this question contains appropriate answers explaining it .命名 React Components 时也要小心,它们需要大写, 这个问题包含解释它的适当答案 (To only solve your problem stick to no.1 of this list, there are some improvements i'd do here overall for code quality and beauty, msg me for more details) (为了只解决您的问题,请坚持使用此列表中的第 1 项,我会在此处总体上对代码质量和美观进行一些改进,请向我发送消息以获取更多详细信息)

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

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