为什么回调后不重新渲染组件?

时间:2020-07-24 06:46:46

标签: javascript reactjs

鉴于以下两个组件,我希望在单击EntryForm中的按钮后,在handleEnttryDelete中的状态更改之后,重新渲染EntryList组件。当前状态改变了,但是用户界面没有更新:

import React, { useState } from "react";

import Button from "@material-ui/core/Button";
import { render } from "@testing-library/react";

const EntryList = (props) => {
  const [entryList, setEntryList] = useState(props.data);

  const handleEntryDelete = (entry) => {
    const newState = entryList.filter(function (el) {
      return el._id != entry._id;
    });
    setEntryList(() => newState);
  };

  return (
    <div>
      {entryList.map((entry) => {
        return (
          <EntryForm entry={entry} handleEntryDelete={handleEntryDelete} />
        );
      })}
    </div>
  );
};

const EntryForm = (props) => {
  const [entry, setEntry] = useState(props.entry);

  return (
    <div>
      <Button onClick={() => props.handleEntryDelete(entry)}>
        {entry._id}
      </Button>
    </div>
  );
};

export default EntryList;

1 个答案:

答案 0 :(得分:1)

您的代码可能有效,但未达到预期目的。将数组映射到组件时,只需使用key

因此,当您删除一个节点时,React可以区分对账期间哪些元素不应该被触摸

<div>
  {entryList.map((entry) => {
    return <EntryForm key={entry._id} entry={entry} handleEntryDelete={handleEntryDelete} />;
  })}
</div>;