【问题标题】:Render child component props on parent state update在父状态更新时渲染子组件道具
【发布时间】:2020-07-18 03:39:57
【问题描述】:

在我的父组件中

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

【问题讨论】:

  • 你能展示一下,你是如何更新父母的状态
  • 家长没有使用React.memo。父组件中的状态是通过 axios 函数完成的。
  • 你能在渲染子元素的地方也添加父元素的 JSX 吗?
  • @UtsavPatel 是的,当然,更新了。

标签: reactjs


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 2021-04-06
    • 2022-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-27
    • 1970-01-01
    • 2018-08-14
    相关资源
    最近更新 更多