首页 > 解决方案 > 在父状态更新时渲染子组件道具

问题描述

在我的父组件中

我有一个布尔状态: 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,即使父组件中的状态已更新。如何使状态/道具同步?

标签: reactjs

解决方案


尝试添加一个调用 setIsLoading 的 useEffect(将其导入到您的 useState 旁边)。下面的伪代码

useEffect(() => {
  if(...){
   setIsLoading(true)
   ...
  } else {
   setIsLoading(false)
  }
}, [var1, ...])

作为 useEffect 的第二个参数,您可以添加要触发效果的更改变量,从而触发状态更新


推荐阅读