2015-11-09 45 views
6

我的應用程序是ES6 React應用程序與react-router。我想稍後將用戶重定向到其他頁面。這裏是我的陣營組成:未指定所需的上下文`router`。檢查`RoutingContext`的渲染方法

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')); 

的問題是,「路由器」屬性不會傳遞到組件。 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 

陣營的版本是0.14.2,反應路由器的版本是1.0.0-RC4 我在哪裏出錯?

+0

我跟着從http://stackoverflow.com/questions/32033247/react-router-transitionto-is-not-a-function/33008706#33008706創建構造函數和更改值建議'路由器'上下文類型,但結果是'transitionTo'仍然不可用。 – taydakov

+0

PayPal開發者有類似的問題,但它被關閉https://github.com/paypal/react-engine/issues/82 – taydakov

回答

4

我不是任何方式的反應路由器專家,但今天早些時候我有同樣的問題。我使用的是React 0.14.2和React-Router 1.0(最近幾天剛剛出現,如果不是最近的話)。雖然調試我注意到做出反應部件上的道具包括歷史(導航的新風格 - https://github.com/rackt/react-router/blob/master/docs/guides/basics/Histories.md

我也使用打字稿,但我的代碼如下所示:

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; 
4

我傾向於說this.context.router不存在了。我遇到了同樣的問題,看起來我們應該使用this.context.history以及this.context.location來實現這些功能。如果我得到了一些工作,我會嘗試更新此響應。

+1

更改'路由器'爲'歷史'做了詭計! – olegz

1

請參閱1.0.0 upgrade guide並使用this.props.historypushStatereplaceStatecontext用於其他組件(不是路由組件)。 從升級指南:

// 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') 
    } 
}) 
相關問題