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

How to emulate window.location with react-router and ES6 classes

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

我发现了这个小纸条 - (https://github.com/rackt/react-router/issues/835) - 我尝试使用 this.context.router.transitionTo(mylink) 但我遇到了上下文问题...

这导致我 (https://github.com/rackt/react-router/issues/1059),但是上下文 returns 和空对象,所以当我尝试做类似的事情时: this.context.router.transitionTo(mylink); 我得到 Cannot read property 'transitionTo' of undefined (如果我尝试在构造函数中执行类似 set this.context = context 的操作)。

不想拖延,但我也厌倦了过多地混淆上下文,因为它是有意未记录的,因为它仍在进行中,所以我已经阅读了。

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

看看来自 react-router 的 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>
    );
  }
});

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

在构造函数中需要:

class SidebarFilter extends React.Component {

    constructor(props, context) {
        super(props, context);

还需要加个静态属性:

SidebarFilter.contextTypes = {
  router: React.PropTypes.func.isRequired
};

然后我可以打电话:

this.context.router.transitionTo(/path-to-link);

如果你为 React-router 使用 browserHistory,生活会更简单。

import {browserHistory} from "react-router";

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

在 React Router 上浪费时间后,我终于切换到基本的 javascript。

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

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

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

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

在这种情况下,我通常使用 hashHistorybrowserHistory,具体取决于您使用的是什么,只需调用 hashHistory.push(<url>)。如果您使用的是 ES6 类,您也可以选择 withRouter Hoc,如前所述 here。这个高阶组件在您的组件中公开了一个名为 router 的道具。使用此道具,您可以使用 this.props.router.push(<url>).

重定向

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

使用useHistory获取历史对象并推送到它以更改url

import { useHistory } from 'react-router-dom';

export default function ModificarUsuario({ url }) {
  const history = useHistory();
  
  function newRoute(){
    history.push('/my-route')
  }
}

使用 react-router-dom 中的 Link,在我的代码片段中我使用了 material-ui <Button>

import {Link} from "react-router-dom";
    
<Button color="primary" 
to="/join" component={Link}>
Join a Room
</Button>

最好的方法是使用 react-router-dom 中的 useHistory。 首先你必须导入它:

import { useHistory } from 'react-router-dom';

然后,您必须通过以下方式声明它的一个实例:

  let history = useHistory();

然后在箭头函数内或任何情况下执行此操作:

history.push("Type here your route link not a domain not anythins else ... .")