在我们的React应用程序中,我们有父子组件。 子组件调用父方法来更新父状态值。 这是示例代码:
//父组件
所以子组件调用父亲的updateParentInformation函数来更新父组件状态,从而重新渲染父组件。这里我有几个问题。
2. 当子组件调用父组件的updateParentInformation函数时,如何避免竞争条件。例如,当子组件1调用updateParentInformation函数并且同时子组件2也调用updateParentInformation函数时,在这种情况下,我们可能会丢失来自一个子组件的更新。
//父组件
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函数来更新父组件状态,从而重新渲染父组件。这里我有几个问题。
In some cases, we may have 100-150 Child components, in such cases our parents will re-render a lot, How to avoid this. We can avoid this throgh this code
.... let recievedUpdates = 0 const updateParentInformation = (childUpdate) => { recievedUpdates++ if(recievedUpdates == items.length { setInformation(information + childUpdates) } }
2. 当子组件调用父组件的updateParentInformation函数时,如何避免竞争条件。例如,当子组件1调用updateParentInformation函数并且同时子组件2也调用updateParentInformation函数时,在这种情况下,我们可能会丢失来自一个子组件的更新。