[英]React hook state updated in parent but child component does not receive new props
I'm using a css grid layout with a differing amount of columns and rows based on screen size.我正在使用 css 网格布局,根据屏幕大小,列和行的数量不同。
import React, { useState, useEffect } from 'react'
function Main() {
const [numRows, setNumRows] = useState(10)
const [numColumns, setNumColumns] = useState(10)
const layoutList = [
<Content {...props} />,
<Content {...props2} />,
<Profile {...props3} numColumns={numColumns} />,
]
const [layout, setLayout] = useState(layoutList)
let gridCount = () => {
//code to count number of columns and rows
//uses setNumRows and setNumColumns passed down as props
}
}
After creating a layout of my components I define a function to count the num of rows and columns.创建组件布局后,我定义了一个 function 来计算行数和列数。
useEffect(() => {
gridCount()
window.addEventListener("resize", gridCount)
})
I add a resize eventlistener which works, I can see that state is being updated in the parent component Main.我添加了一个有效的调整大小事件监听器,我可以看到 state 正在父组件 Main 中更新。 However when I check the state of the child component Profile I see that it was initialized with 10 but never gets accessed again, no new props are being sent to even though the Main state is being updated correctly.
但是,当我检查子组件 Profile 的 state 时,我看到它已用 10 初始化,但再也不会被访问,即使主 state 正在正确更新,也没有发送新的道具。 I'm trying to get a rerender in the child but I'm unsure why the parent is not sending updated props, any state change in the parent should cause a rerender correct?
我正在尝试重新渲染孩子,但我不确定为什么父母没有发送更新的道具,父母中的任何 state 更改都应该导致重新渲染正确吗?
Hard to tell exactly from the code available, but I suspect the children do not receive the new props because those children are stored in state and never updated.很难从可用的代码中准确判断,但我怀疑孩子们没有收到新的道具,因为这些孩子们存储在 state 中并且从未更新过。
To fix this you should update the children whenever you update numRows
or numColumns
.要解决此问题,您应该在更新
numRows
或numColumns
时更新子级。 Since there isn't usually a good reason to store children in a state variable (and it can lead to issues like this where you have to manually tell the children to update instead of letting React handle that), I would recommend removing the state storage for layout
entirely and just rendering the children like usual.由于通常没有充分的理由将孩子存储在 state 变量中(并且它可能导致这样的问题,您必须手动告诉孩子更新而不是让 React 处理),我建议删除 state 存储完全用于
layout
,只是像往常一样渲染孩子。 Just use layoutList
directly in your returned element.只需在返回的元素中直接使用
layoutList
即可。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.