【问题标题】:Cannot pass props to React Router page component, TS2322无法将道具传递给 React Router 页面组件,TS2322
【发布时间】:2021-04-06 18:00:49
【问题描述】:

我正在与 typescript 编译器作斗争,试图在导出的组件中期待 props,该组件呈现为 React Router 页面。 (我用的是最新版react-router-dom,5.2.0。

在我的库代码中:

interface AppProps {
    baseApiUrl?: string
}
export function App({
    baseApiUrl = ''
}: AppProps): React.ReactElement<AppProps> { /* my component code */ }

在我看到打字稿错误的实现代码中:

export function Sandbox(): React.ReactElement {
    return (
        <BrowserRouter>
            <Switch>
                <Route path="*">
                    <App baseApiUrl="http://localhost:3000"  />
                </Route>
            </Switch>
        </BrowserRouter>
    )
}

为什么我会收到此打字稿错误?

TS2322: Type '{ baseApiUrl: string; }' is not assignable to type 'IntrinsicAttributes & AppProps'.
  Property 'baseApiUrl' does not exist on type 'IntrinsicAttributes & AppProps'.
     8 |            <Switch>
     9 |                <Route path="*">
  > 10 |                    <App baseApiUrl="http://localhost:3000"  />
       |                         ^^^^^^^^^^
    11 |                </Route>
    12 |            </Switch>
    13 |        </BrowserRouter>

这个 IntrinsicAttributes 是从哪里来的?我该怎么做才能让编译器满意?

我已经尝试过像这样重写函数签名:

export const App: React.FC<AppProps> = (props) => { /* my component code */ }

并得到相同的编译器错误。

【问题讨论】:

  • 为什么不在rendercomponent 属性上渲染App,所以history 作为属性传递(通过路由属性),或者使用useHistory React 钩子来访问@ 987654331@ 来自路由上下文?
  • 这是个好建议。我编辑掉了任何history 传递并改用useHistory,不幸的是编译器仍然不喜欢它。我编辑了帖子以反映这些变化。

标签: reactjs typescript react-router tsc


【解决方案1】:

回答你不需要做任何事情来让编译器满意。

正如您在https://codesandbox.io/s/vibrant-wood-5clyq?file=/src/App.tsx 看到的那样,您共享的代码很好,所以肯定有一些其他代码以某种方式损坏。例如,您有两个都称为 AppProps 的东西,产生错误的那个与您共享的那个不同。鉴于您没有分享 minimal reproducible example,这只是一个猜测。

也许你可以通过分叉我上面分享的沙箱来制作一个可重现的例子?

【讨论】:

  • 你是对的。我自己把它放在一个codeandbox中,没有看到错误。它与我的开发环境中的某些东西有关。
猜你喜欢
  • 2014-11-19
  • 2020-12-21
  • 2018-04-25
  • 2018-07-17
  • 2015-09-21
  • 2018-12-14
  • 2015-03-08
  • 2016-03-19
  • 2018-05-19
相关资源
最近更新 更多