我的应用程序是带有react-router的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
}

和react-router的路由表:
render(
    <Router>
        <Route path='/' component={ App }>
            <IndexRoute component={ Component } />
        </Route>
    </Router>
, document.getElementById('app-container'));

问题是“路由器”属性未传递到组件中。 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-router版本是1.0.0-rc4
我在哪里犯错?

最佳答案

我无论如何都不是反应路由器专家,但今天早些时候我遇到了同样的问题。我正在使用React 0.14.2和React-Router 1.0(这是最近几天才发布的,如果不是最近的话)。调试时,我注意到React组件上的 Prop 包括历史记录(新的导航样式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;

08-08 04:21