如何使用react-router和ES6类模拟window.location

Ben*_*Ben 20 reactjs react-router

我正在使用react-router,所以我在<Link />整个应用程序中使用该组件作为我的链接,在某些情况下我需要根据用户输入动态生成链接,所以我需要类似的东西 window.location,但没有页面刷新.

我找到了这个小笔记 - (https://github.com/rackt/react-router/issues/835) - 我尝试过使用,this.context.router.transitionTo(mylink)但我遇到了上下文问题...

这导致我(https://github.com/rackt/react-router/issues/1059),但上下文返回和空对象,所以当我尝试todo之类的东西:this.context.router.transitionTo(mylink);我得到Cannot read property 'transitionTo' of undefined(如果我尝试做类似的事情this.context =构造函数中的上下文).

不要拖延,但我也厌倦了过多的上下文,因为它没有故意记录,因为它仍然是一项正在进行的工作,所以我读过.

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

Ben*_*Ben 13

在这里找到了一个解决方案:https://github.com/rackt/react-router/issues/975,在这里:https://github.com/rackt/react-router/issues/1499

构造函数需要:

class SidebarFilter extends React.Component {

    constructor(props, context) {
        super(props, context);
Run Code Online (Sandbox Code Playgroud)

还需要添加一个静态属性:

SidebarFilter.contextTypes = {
  router: React.PropTypes.func.isRequired
};
Run Code Online (Sandbox Code Playgroud)

然后我可以打电话:

this.context.router.transitionTo(/path-to-link);
Run Code Online (Sandbox Code Playgroud)


小智 12

如果您使用BrowserHistory用于React-router,生活会更简单.

import {browserHistory} from "react-router";

functionName() {
 browserHistory.push("/path-to-link");
}
Run Code Online (Sandbox Code Playgroud)

  • 错误:'react-router'不包含名为'browserHistory'的导出. (5认同)

Pri*_*han 9

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

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

    路径路径="*"组件= {NotFound}

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

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

  • 不要陷入[认为图书馆应该规定如何做所有事情的陷阱](http://amasad.me/2016/01/03/overcoming-intuition-in-programming/)。如果要对JavaScript中的位置进行操作,则可以使用window.location。没有理由为什么外反应应该有所不同。 (3认同)
  • 这个问题被标记为 react-router——如果你主张不使用该工具,你应该详细解释为什么它不起作用 (2认同)