React useState 钩子不会触发子组件重新渲染
React useState hook isn't triggering child component re-render
在 React 中,我有一个功能组件,在单击子组件按钮(“GenerateButton”)时,应该启动另一个子组件(“UsersView”)的渲染,然后显示一个从 REST API.
中提取的用户列表
调试时,我注意到即使“dataShouldLoad”状态切换为 true,它甚至不会尝试开始加载“UsersView”组件中的代码,尽管“dataShouldLoad”已被传递和使用作为支柱。为什么是这样?我该怎么办?
这是我的简化代码片段:
import React, {useState} from 'react';
import GenerateButton from './GenerateButton.js';
import UsersView from './UsersView.js';
export default function GenerateReportView() {
const [dataShouldLoad, setDataShouldLoad] = useState(false);
const [dataHasLoaded, setDataHasLoaded] = useState(false);
const handleGenerateButtonClick = () => {
// By toggling this to true, I am attempting to kick off
// the "UsersView" to fetch its data, and display here
setDataShouldLoad(true);
}
return (
<div>
{dataHasLoaded ?
<UsersView dataShouldLoad={dataShouldLoad} setDataHasLoaded={setDataHasLoaded}/>
: <h2>Click Button to Load</h2>
}
<GenerateButton onClick={handleGenerateButtonClick}/>
</div>
);
}
现在,三元正在计算 dataHasLoaded
,而不是 dataShouldLoad
。更改为 dataShouldLoad
,它将呈现。
当您为 useState
挂钩设置新状态时,组件 useState
处于重新渲染状态,并且子组件通常也会重新渲染。在您的代码中,UsersView
甚至不是 DOM 中 GenerateReportView
的子组件,正如您所说的那样 - 当 dataHasLoaded
为假时,UsersView
不会作为子组件出现。
在 React 中,我有一个功能组件,在单击子组件按钮(“GenerateButton”)时,应该启动另一个子组件(“UsersView”)的渲染,然后显示一个从 REST API.
中提取的用户列表调试时,我注意到即使“dataShouldLoad”状态切换为 true,它甚至不会尝试开始加载“UsersView”组件中的代码,尽管“dataShouldLoad”已被传递和使用作为支柱。为什么是这样?我该怎么办?
这是我的简化代码片段:
import React, {useState} from 'react';
import GenerateButton from './GenerateButton.js';
import UsersView from './UsersView.js';
export default function GenerateReportView() {
const [dataShouldLoad, setDataShouldLoad] = useState(false);
const [dataHasLoaded, setDataHasLoaded] = useState(false);
const handleGenerateButtonClick = () => {
// By toggling this to true, I am attempting to kick off
// the "UsersView" to fetch its data, and display here
setDataShouldLoad(true);
}
return (
<div>
{dataHasLoaded ?
<UsersView dataShouldLoad={dataShouldLoad} setDataHasLoaded={setDataHasLoaded}/>
: <h2>Click Button to Load</h2>
}
<GenerateButton onClick={handleGenerateButtonClick}/>
</div>
);
}
现在,三元正在计算 dataHasLoaded
,而不是 dataShouldLoad
。更改为 dataShouldLoad
,它将呈现。
当您为 useState
挂钩设置新状态时,组件 useState
处于重新渲染状态,并且子组件通常也会重新渲染。在您的代码中,UsersView
甚至不是 DOM 中 GenerateReportView
的子组件,正如您所说的那样 - 当 dataHasLoaded
为假时,UsersView
不会作为子组件出现。