簡體   English   中英

故障排除備忘錄調用 React+Typescript

[英]Troubleshooting memo call React+Typescript

我需要你的幫助。 最近開始學習Typescript,遇到一個React的問題。 我嘗試用 React.memo() 包裝我的路由器。 像這樣:

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>

  )
});

我的RouterPropsInterface看起來像這樣:

export interface RouterPropsInterface {
    isAuth: boolean,
}

但在那種情況下,我還有其他問題:

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

“反應”:“^17.0.2”,“打字稿”:“^4.6.2”

我不想添加 eslint-disablers,只是想了解我做錯了什么。

謝謝!

使用React.memo包裝組件時,React 不再推斷displayName屬性。 所以,你需要這樣設置。

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

關於道具類型,您可以通過添加道具類型來滿足這一點,如下所示:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM