【问题标题】:In react-router, what is the type of this.context.router?在 react-router 中,this.context.router 的类型是什么?
【发布时间】:2016-06-03 03:50:28
【问题描述】:

为了设置上下文,我在 lesson 12 of react-router-tutorial,但随着我的跟进,我实际上是在 TypeScript 中做所有事情。在教程的这一点上,在几个 React 组件中,有一个叫做 Repos

export class Repos extends React.Component<ReposProps, {}> { ... }

这是在Router 中创建的

<Router history={browserHistory}>
    {/* ... */}
    <Route path="/repos" component={Repos}>{/* ... */}</Route>
    {/* ... */}
</Router>

Repos 中的某处是一种方法,它从 HTML 表单中获取一些参数并构造一条新路径以将浏览器定向到:

handleSubmit(event: React.FormEvent) {
    /* ... (define userName and repo vars) */
    const path = `/repos/${userName}/${repo}`
    this.context.router.push(path);
}

我的问题是最后一行的contextrouter 的类型是什么?

the React documentation on Contexts 中,我了解到上下文通常在每个元素中定义。这里似乎一个绝妙的主意是在Repos 中定义context,其接口扩展自react-router's TypeScript type definitions 中定义的某个接口

interface ReposContext extends Something /* ??? */ { }

在这里,Something 会将router 定义为具有push 方法的某种类型。

API 并没有说 Router 有一个方法 push 虽然 Glossary 有,这令人困惑。无论如何,DefinitelyTyped 上的类型定义并没有在 Router 下定义 push 方法(虽然我不相信它们是完美的,但这种遗漏对我来说似乎不是偶然的)

同样的 API 确实指出了 RouterContext,其中提到了 context.router -- context.router 确实定义了 push() 以及许多其他方法。

然后我注意到在 react-router 的类型定义的 history.d.ts 中,接口 History 具有所有相同的方法(加上更多

也许这个界面正在接近。它没有像我想要的那样扩展任何东西(也许这是 react-router 类型改进的空间),但它有我需要的东西。

interface ContextRouter extends History { }

interface ReposContext {
    router: ContextRouter
}

我仍然持怀疑态度,因为尽管 ContextRouter 扩展了 History 并不完全有意义

【问题讨论】:

    标签: reactjs typescript react-router


    【解决方案1】:

    我使用 ReactRouter.RouterOnContext:

    context: {
        router: ReactRouter.RouterOnContext
    }
    

    【讨论】:

      【解决方案2】:

      我已经通过深入研究 react-router 代码来解决这个问题。通过弄清楚路由器是如何创建的,我最终找到了match.js,在那里我发现路由器实际上是通过将历史传递给 createRouterObject 来创建的,它只是创建了一个与历史以及其他几个属性相同的对象属性。

      路由器的类型确实扩展了历史记录。

      【讨论】:

        猜你喜欢
        • 2016-06-02
        • 2019-03-17
        • 2019-05-01
        • 2016-11-20
        • 2018-05-25
        • 2021-02-25
        • 2023-03-24
        • 2017-08-28
        • 2018-07-16
        相关资源
        最近更新 更多