未指定必需的上下文“router”.检查“RoutingContext”的呈现方法

Required context `router` was not specified. Check the render method of `RoutingContext`

本文关键字:方法 RoutingContext 检查 router 上下文 未指定      更新时间:2023-09-26

我的应用程序是带有React路由器的ES6 React应用程序。我想在一个小延迟后将用户重定向到另一个页面。这是我的React组件:

import React from 'react'
import { Navigation } from 'react-router'
export default class Component extends React.Component {
    render () {
        return (
            <div>Component content</div>
        )
    }
    componentDidMount () {
        setTimeout(() => {
            // TODO: redirect to homepage
            console.log('redirecting...');
            this.context.router.transitionTo('homepage');
        }, 1000);
    }
}
Component.contextTypes = {
    router: React.PropTypes.func.isRequired
}

并反应路由器路由表:

render(
    <Router>
        <Route path='/' component={ App }>
            <IndexRoute component={ Component } />
        </Route>
    </Router>
, document.getElementById('app-container'));

问题是"router"属性未传递到组件中。Chrome控制台的内容是:

Warning: Failed Context Types: Required context `router` was not specified in `Component`. Check the render method of `RoutingContext`.
redirecting...
Uncaught TypeError: Cannot read property 'transitionTo' of undefined

React版本为0.14.2,React路由器版本为1.0.0-rc4我在哪里犯错误?

我无论如何都不是react路由器专家,但今天早些时候我也遇到了同样的问题。我使用的是React 0.14.2和React Router 1.0(这是最近几天才发布的)。在调试时,我注意到React组件上的道具包括历史(新的导航风格-https://github.com/rackt/react-router/blob/master/docs/guides/basics/Histories.md)

我也在使用TypeScript,但我的代码看起来如下:

import React = require('react');
import Header = require('./common/header.tsx');
var ReactRouter = require('react-router');
interface Props extends React.Props<Home> {
    history: any
}
class Home extends React.Component<Props, {}> {
    render(): JSX.Element {
        return (
            <div>
                <Header.Header MenuItems={[]} />
                <div className="jumbotron">
                    <h1>Utility</h1>
                    <p>Click on one of the options below to get started...</p>
                    {<a className="btn btn-lg" onClick={() => this.props.history.pushState(null, '/remoteaccess') }>Remote Access</a>}
                    {<a className="btn btn-lg" onClick={() => this.props.history.pushState(null, '/bridge') }>Bridge</a>}
                </div>
            </div>
        );
    }
}
module.exports = Home;

我倾向于说this.context.router已经不存在了。我遇到了同样的问题,看起来我们应该使用this.context.historythis.context.location来实现这些功能。如果我得到了一些工作,我会尝试更新此响应。

请参阅1.0.0升级指南,并将this.props.historypushStatereplaceState一起使用。context用于其他组件(而不是路由组件)。来自升级指南:

// v1.0
// if you are a route component...
<Route component={Assignment} />
var Assignment = React.createClass({
  foo () {
    this.props.location // contains path information
    this.props.params // contains params
    this.props.history.isActive('/pathToAssignment')
  }
})