简体   繁体   English

故障排除备忘录调用 React+Typescript

[英]Troubleshooting memo call React+Typescript

I need your help.我需要你的帮助。 Started learning Typescript recently and got one problem with React.最近开始学习Typescript,遇到一个React的问题。 I try to wrap my Router with React.memo().我尝试用 React.memo() 包装我的路由器。 Smth like this:像这样:

export const Router = React.memo<RouterPropsInterface>(({ isAuth }) => {

  if (!isAuth) {
      return (
          <Suspense fallback={<Loader text={""}/>}>
              <Routes>
                  <Route path={'/'} element={<LoginPage/>}/>
                  <Route path={'*'} element={<LoginPage/>}/>
                  <Route path={'register'} element={<RegisterPage/>}/>
              </Routes>
          </Suspense>
      )
  }

  return (
      <Suspense fallback={<Loader text={""}/>}>
          <Routes>
              <Route path={'create'} element={<AddCard/>}/>
              <Route path={'posts'} element={<UsersList/>}/>
              <Route path={'/'} element={<Home/>}/>
              <Route path={"*"} element={<Home/>}/>
          </Routes>
      </Suspense>

  )
});

My RouterPropsInterface looks like this:我的RouterPropsInterface看起来像这样:

export interface RouterPropsInterface {
    isAuth: boolean,
}

But in that case, I have other problems:但在那种情况下,我还有其他问题:

src/routers/Router.tsx
  Line 12:23:  Component definition is missing display name  react/display-name
  Line 12:59:  'isAuth' is missing in props validation       react/prop-types

"react": "^17.0.2", "typescript": "^4.6.2" “反应”:“^17.0.2”,“打字稿”:“^4.6.2”

I don't want to add eslint-disablers, just wanna understand what I'm doing wrong.我不想添加 eslint-disablers,只是想了解我做错了什么。

Thanks!谢谢!

When wrapping a component with React.memo , the displayName property is no longer inferred by React.使用React.memo包装组件时,React 不再推断displayName属性。 So, you need to set it like so.所以,你需要这样设置。

export const Router = React.memo(({ isAuth }) => {...}
Router.displayName = "Router"

Regarding prop types, you can satisfy this by adding prop types like so:关于道具类型,您可以通过添加道具类型来满足这一点,如下所示:

export const Router = React.memo(({ isAuth }: {isAuth: RouterPropsInterface }) => {...}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM