【问题标题】:Where should I utilize useEffect in my HOC which is receiving props in React?我应该在我的 HOC 中哪里使用 useEffect 来接收 React 中的道具?
【发布时间】:2020-02-12 15:19:13
【问题描述】:

我有这个高阶函数:

它应该基于我在条件中使用的一些道具来渲染我的元素。

function GenericIsUserLoggedInLink({ isLoggedIn, logOutUser, route, anchorText }) {
 if (isLoggedIn) {
  if (anchorText === undefined) {
   return <Link href="/"><a onClick={() => logOutUser()}>Log out!</a></Link>
  } else if (anchorText) {
   return <Link href={route}><a>{anchorText}</a></Link>
  } else {
   return null
  }
 } else {
  return  <Link href="/login"><a>Log in!</a></Link>
 }
}

它从 *Parent class Component 获取道具,它从 redux 商店获取这些道具。

*链接到我的仓库以检查整个文件

上面的 HOC 几乎是完美的,但是当有人出于某种原因尝试注销时,我在导航的左侧链接上看到了这种行为。

我开始认为问题可能是由于重新渲染而我没有做任何事情。

我最近在一个组件类中了解到,当组件发生变化时,您会使用componentDidUpdate 生命周期方法。

所以我做了一些挖掘广告,发现这个post 关于在 HOC 中应该使用的方法。我的问题是它应该去哪里?

其实我也想过这样的事情,但是没用……

导入反应,{ useEffect } from 'react';

function GenericIsUserLoggedInLink({ isLoggedIn, logOutUser, route, anchorText }) {
 if (isLoggedIn) {
  if (anchorText === undefined) {
   return <Link href="/"><a onClick={() => logOutUser()}>Log out!</a></Link>
  } else if (anchorText) {
   return <Link href={useEffect(() => {
 {route} // Just took a stab, on second blush I thought it wasn't that crazy!!

}, [路线]);}>{anchorText} } 别的 { 返回空 } } 别的 { 返回登录! } }

无论如何,我只是想了解一下为什么当您单击注销按钮时,其他导航链接也显示登录...

【问题讨论】:

  • 它似乎完全按照您的要求做,请详细说明您不期望的行为
  • @Drax 啊抱歉我被带走了...我更新了问题。
  • 尝试为条件中的每个链接组件添加一个唯一的 key 属性。

标签: reactjs state higher-order-functions high-order-component react-lifecycle-hooks


【解决方案1】:

在您的linked code 中,您在左侧导航链接上使用您的 HOC,包括您的链接“个人资料”和“仪表板”,并且在您的 HOC 内部,主要条件是:

if (isLoggedIn) {
  ...
} else {
  return  <Link href="/login"><a>Log in!</a></Link>
}

因此,如果您未登录 (isLoggedin === false),则返回带有“登录!”的 Link。写在里面,这就是渲染而不是你的导航链接。 和其他提到的没有太大关系。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多