【发布时间】:2022-06-29 21:49:51
【问题描述】:
在我们的反应应用程序中,我们有父子组件。子组件调用父方法更新父状态值。这是示例代码
//父组件
const parent = ({ items }) => {
const [information, setInformation] = useState([]);
const updateParentInformation = (childUpdate) => {
setInformation(information + childUpdates)
}
return (
<div>
<div>{information}</div>
...
{items.map((item) => {
return (
<ChildComponent item={item} updateParentInformation={updateParentInformation} />
)})}
</div>
)
}
//子组件
const ChildComponent = ({ item, updateParentInformation }) => {
useEffect(() => {
const cardInformation = calculateCardInformation(item)
updateParentInformation(cardAmpScripts)
}, [item])
return (
<div>
.....
</div>
)
}
所以子组件调用父组件的updateParentInformation函数来更新父状态,从而重新渲染父组件。我这里有几个问题
-
在某些情况下,我们可能有 100-150 个子组件,在这种情况下我们的父母会重新渲染很多,如何避免这种情况。我们可以通过这段代码避免这种情况
.... let recievedUpdates = 0 const updateParentInformation = (childUpdate) => { recievedUpdates++ if(recievedUpdates == items.length { setInformation(information + childUpdates) } }
如果这是一个可能的解决方案,那么我有问题 2
- 当子组件调用父组件的 updateParentInformation 时如何避免竞态条件。例如,孩子 1 被称为 updateParentInformation 函数,同时孩子 2 也被称为 updateParentInformation,在这种情况下,我们可能会丢失一个孩子的更新。
【问题讨论】:
-
对于第一个问题,您可以使用 React.memo() (reactjs.org/docs/react-api.html#reactmemo) 以便仅在其道具发生变化时才重新渲染组件
-
你能在codesandbox.io或类似网站上创建一个可运行的minimal reproducible example吗?我将能够对这种行为有所了解。
标签: reactjs use-effect use-ref