2015-07-21 72 views
13

我使用react-router,因此我在整个应用中使用<Link />组件作为链接,在某些情况下我需要根据用户动态生成链接输入,所以我需要类似window.location,但没有页面刷新。如何使用react-router和ES6类来模拟window.location

我发现这个小纸条 - (https://github.com/rackt/react-router/issues/835) - 我试着用this.context.router.transitionTo(mylink),但我在使用方面的问题......

害得我(https://github.com/rackt/react-router/issues/1059),但背景回报和空对象,所以当我尝试了这样的事情:this.context.router.transitionTo(mylink);我得到Cannot read property 'transitionTo' of undefined(如果我尝试在构造函数中设置this.context = context)。

不要拖延,但我也厌倦了与上下文搞乱太多,因为它仍然是一个正在进行的工作,所以我读过。

有没有人遇到类似的问题?

回答

1

看看反应路由器中的Navigation mixin。 http://rackt.github.io/react-router/#Navigation

从文档:

var Navigation = require('react-router').Navigation; 

React.createClass({ 
    mixins: [Navigation], 

    render: function() { 
    return (
     <div onClick={() => this.transitionTo('foo')}>Go to foo</div> 
     <div onClick={() => this.replaceWith('bar')}>Go to bar without creating a new history entry</div> 
     <div onClick={() => this.goBack()}>Go back</div> 
    ); 
    } 
}); 
+4

谢谢@paulshen。不幸的是我使用的是ES6类,所以我不能使用mixins。我不确定是否有可能,但我试图导入导航方法,例如'从'react-router''导入{Navigation} ...尝试查看是否有可能,遇到transitionTo中存在的'this.context'的一些问题,我现在试图弄清楚。 – Ben

8

如果使用browserHistory的阵营路由器,生活更简单。

import {browserHistory} from "react-router"; 

functionName() { 
browserHistory.push("/path-to-link"); 
} 
2

与反应路由器浪费时间后,我终于切换到基本的JavaScript。

  1. 为您重定向创建一个组件:

    路由路径= “*” 组件= {} NOTFOUND

  2. 在组件使用了window.location重定向:

    componentDidMount() { 
         if (typeof window !== 'undefined') { 
          window.location.href = "http://foo.com/error.php"; 
         } 
    } 
    
0

在这种情况下,我通常使用hashHistorybrowserHistory dependi只需要拨打hashHistory.push(<url>)即可。如果您使用的是ES6课程,则还可以参考here提到的由react-router提供的withRouter Hoc。这个更高阶的组件会在您的组件中显示一个名为router的道具。使用此道具您可以使用this.props.router.push(<url>)重定向。

如果您必须从上下文中使用路由器,您将必须提供@ Ben的答案中提到的上下文类型。