[英]Why does the component not re-render after callback?
Given the following two components, I expect the EntryList component to re-render after the state changes in the handleEnttryDelete after the button in EntryForm is clicked.鉴于以下两个组件,我希望在单击 EntryForm 中的按钮后,在 handleEnttryDelete 中的 state 更改后, EntryList 组件将重新呈现。 Currently the state changes, but the UI isn't updating itself:目前 state 发生变化,但 UI 并未自行更新:
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;
Your code probably works, but not as intended.您的代码可能有效,但未达到预期。 You just have to use key
while mapping arrays to components.您只需在将 arrays 映射到组件时使用key
。
Therefore, React can distinguish which elements should not be touched during reconciliation when you delete one of the nodes因此,React 可以区分当你删除其中一个节点时,在对账过程中哪些元素不应该被触动
<div>
{entryList.map((entry) => {
return <EntryForm key={entry._id} entry={entry} handleEntryDelete={handleEntryDelete} />;
})}
</div>;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.