reactjs - 在父状态更新时渲染子组件道具
问题描述
在我的父组件中:
我有一个布尔状态:
const [isLoading, setIsLoading] = useState<boolean>(true);
我发送给子组件:
return (
<OrganisationPersonsLister personsStripped={personsStripped} isLoading={isLoading} />
);
在我的子组件中:我收到了道具
const OrganisationPersonsLister = React.memo((props: { isLoading: boolean }) => {
}
并且根据布尔值,我希望它呈现不同的组件。
return (
<section className="org-person-lister">
{
(isLoading)
? <Spinner />
: <PopTable title={"title"} columns={columns} data={personsStripped} />
}
</section>
)
我如何更新父组件中的状态:
const viewOrganisation = (orgId: string) => {
const org = orgList.find(o => o.id === orgId);
if (org !== undefined) {
setIsLoading(true)
setChosenOrg(org);
PersonApi.fetchPersonsByOrganisationId(orgId).then(response => {
console.log("fetchPersonByOrganisationId: ", response)
setIsLoading(false)
setPersonsStripped(response)
}).catch(err => {
console.error("Error occurred: ", err);
setIsLoading(false)
setPersonsStripped([])
});
}
};
问题是它在初始加载时执行一次,然后在子组件中保持为 false,即使父组件中的状态已更新。如何使状态/道具同步?
解决方案
尝试添加一个调用 setIsLoading 的 useEffect(将其导入到您的 useState 旁边)。下面的伪代码
useEffect(() => {
if(...){
setIsLoading(true)
...
} else {
setIsLoading(false)
}
}, [var1, ...])
作为 useEffect 的第二个参数,您可以添加要触发效果的更改变量,从而触发状态更新
推荐阅读
- math - 求直线任意阶非球面透镜曲面的解
- python - 拆分文本包含空格,但将引号内的单词作为一个单元
- mysql - 无法安装 mysql community server 8.0 windows 10。我已经安装了 Server 5.7 和 Workbench 8.0 CE
- authentication - DocusignAPI SOAP 通过 Post,不使用任何 SDK
- ios - 如何声明正确的内容以将另一个 swiftui 文件导入到 contentview 文件中?
- kotlin - Google MapView 用 Kotlin 实现 OnMapReadyCallback
- redis - Rpush不添加特定键
- c# - 如何同步调用异步方法?
- c# - 当空引用似乎不可能时,为什么我们会收到可能的取消引用空引用警告?
- ios - 打开 Thread Sanitizer 会产生信号 SIGABRT