首页 > 解决方案 > 单击项目覆盖另一个数据

问题描述

我有这个应用程序,用户可以在其中留下他们的评论并对特定的汽车进行评分。
https://codesandbox.io/s/public-antd-modal-forked-hj6bh?file=/App.js
现在存在一个问题,当用户首先输入一条消息,然后在点击星号后点击开始评分输入中的文本消失,但 id 不应清空输入,这应该仅在单击OK按钮后

 const setRate = (category, rate) => {
    const newData = [...data];
    let index = newData.findIndex((c) => c.carCat === category);
    newData[index] = Object.assign(newData[index], { rate });

    setData(newData);
  };

  const setSingleComment = (category, comment) => {
    comments[category] = comment;
    setComments(comments);
  };

  function handleOk() {
    const newData = [...data];

    for (let category of Object.keys(comments)) {
      let index = newData.findIndex((c) => c.carCat === category);
      newData[index].comments.push(comments[category]);
    }

    setData(newData);
    setComments({});
    setVisible(false);
  }

为什么会发生以及如何解决这个问题?

标签: reactjs

解决方案


更新作为对象或数组的状态,应始终在顶层返回一个新引用,否则 react 将不会在对象中看到“更改”(它使用浅检查)并且您的组件不会重新渲染。

  const setSingleComment = (category, comment) => {
    comments[category] = comment;
    setComments({ ...comments }); //a new object needs to be created here, otherwise react wont rerender.
  };

坚持将状态保存在一个地方。在这种情况下,在顶层。这意味着从SetData组件中删除状态,并简单地传递其值,并实现突变方法。

function SetData({ rate, singleComment, onRateChange, onSingleCommentChange }) {
  //only need to store state in a single place. In this case, at the app level
  const handleRateChange = (e) => {
    onRateChange(e);
  };

  function handleCommentChange(e) {
    const text = e.target.value;
    onSingleCommentChange(text);
  }

  return (
    <div>
      <Rate value={rate} onChange={handleRateChange} />
      <input
        value={singleComment ? singleComment : ""}
        onChange={handleCommentChange}
      />
    </div>
  );
}

在CodeSandbox上查看更新的代码

我希望我已经意识到你的意图。


推荐阅读