英文:
Component's useEffect() not called when component is rendered, but only after it is "hidden"
问题
我有以下的父组件:
const Details = ({ processing, toProcess, deepDiving }) => {
const [ddFile, setDdFile] = useState(null)
if (!deepDiving)
return <Summary {...{ processing, toProcess, setDdFile }} />
else
return <DeepDive {...{ ddFile }} />
}
在组件DeepDive中,我有一个useEffect()
函数:
const DeepDive = ({ ddFile: file }) => {
const db = read(file)
const [ary, setAry] = useState([])
useEffect(() =>
async function add() { ...
}, [file]
)
return <table>
<tbody>
<tr><th>Name</th><th>Rank</th></tr>
{ary.map((m, i) => <DeepDiveRow key={i} {...{ m }} />)}
</tbody>
</table>
}
状态变量deepDiving最初为false,将父组件中的子Summary渲染出来。当deepDiving被设置为true时,DeepDive子组件被渲染,但它的useEffect
不会被调用。当deepDiving再次被设置为false时,DeepDive的useEffect
随后被执行(!),尽管它先前已被渲染但现在在父组件中不可见。
请注意,如果我将useEffect
的第二个参数从更改为
[]
,我会得到相同的结果。
英文:
I have the following parent component:
const Details = ({ processing, toProcess, deepDiving }) => {
const [ddFile, setDdFile] = useState(null)
if (!deepDiving)
return <Summary {...{ processing, toProcess, setDdFile }} />
else
return <DeepDive {...{ ddFile }} />
}
in component DeepDive, I have a useEffect()
function:
const DeepDive = ({ ddFile: file }) => {
const db = read(file)
const [ary, setAry] = useState([])
useEffect(() =>
async function add() { ...
},
)
return <table>
<tbody>
<tr><th>Name</th><th>Rank</th></tr>
{ary.map((m, i) => <DeepDiveRow key={i} {...{ m }} />)}
</tbody>
</table>
}
The state variable deepDiving is initially false, rendering the child Summary in the parent component. When deepDiving is set to true, then the DeepDive child component is rendered, but its useEffect is not called. When deepDiving is set back to false, then DeepDive's useEffect is then executed(!), even though it had been previously rendered but is now not visible in the parent component.
Note that if I change the second argument of useEffect from to
[]
, I get the same result.
答案1
得分: 1
你的useEffect
调用似乎只返回一个清理函数。清理函数在组件卸载后运行。
你可以尝试将useEffect
调用重新编写如下:
useEffect(() => {
async function add() { ...
}
// 可能需要在这里调用add:
add();
}, [file])
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论