鉴于以下两个组件,我希望在单击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;
答案 0 :(得分:1)
您的代码可能有效,但未达到预期目的。将数组映射到组件时,只需使用key
。
因此,当您删除一个节点时,React可以区分对账期间哪些元素不应该被触摸
<div>
{entryList.map((entry) => {
return <EntryForm key={entry._id} entry={entry} handleEntryDelete={handleEntryDelete} />;
})}
</div>;