使用react router,我可以使用Link元素来创建由react route本地处理的链接。

我看到它在内部调用this.context.transitionTo(…)。

我想做导航。不是来自链接,而是来自下拉选择(例如)。我如何在代码中执行此操作?this.context是什么?

我看到了导航混合,但我可以在没有混合的情况下这样做吗?


当前回答

如果您碰巧通过react router redux将RR4与redux配对,那么也可以使用react router-redux中的路由操作创建器。

import { push, replace, ... } from 'react-router-redux'

class WrappedComponent extends React.Component {
  handleRedirect(url, replaceState = true) {
    replaceState
      ? this.props.dispatch(replace(url))
      : this.props.dispatch(push(url))
  }
  render() { ... }
}

export default connect(null)(WrappedComponent)

如果您使用redux thunk/saga来管理异步流,请在redux操作中导入上述操作创建者,并使用mapDispatchToProps连接到React组件可能会更好。

其他回答

也许不是最好的解决方案,但它可以完成任务:

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

// Create functional component Post
export default Post = () => (
    <div className="component post">

        <button className="button delete-post" onClick={() => {
            // ... delete post
            // then redirect, without page reload, by triggering a hidden Link
            document.querySelector('.trigger.go-home').click();
        }}>Delete Post</button>

        <Link to="/" className="trigger go-home hidden"></Link>

    </div>
);

基本上,与一个操作相关的逻辑(在本例中为删除后操作)最终将调用重定向触发器。这并不理想,因为您将在标记中添加DOM节点“触发器”,以便在需要时方便地调用它。此外,您将直接与DOM交互,这在React组件中可能是不需要的。

不过,这种类型的重定向并不经常需要。因此,在组件标记中添加一两个额外的隐藏链接并不会造成太大的伤害,特别是如果您为它们提供了有意义的名称。

在基于类的组件中编程导航。

import { Redirect } from "react-router-dom";

class MyComponent extends React.Component{
    state = {rpath: null}

    const goTo = (path) => this.setState({rpath: path});

    render(){
        if(this.state.rpath){
            return <Redirect to={this.state.rpath}/>
        }
        .....
        .....
    }
}

带挂钩的React Router v6

import {useNavigate} from 'react-router-dom';
let navigate = useNavigate();
navigate('home');

为了浏览浏览器历史,

navigate(-1); ---> Go back
navigate(1);  ---> Go forward
navigate(-2); ---> Move two steps backward.

以下是最简单、最干净的方法,大约是当前的React Router 3.0.0和ES6:

使用ES6反应路由器3.x.x:

import { withRouter } from 'react-router';

class Example extends React.Component {
   // use `this.props.router.push('/some/path')` here
};

// Export the decorated class
export default withRouter(Example);

或者,如果不是默认类,则导出如下:

withRouter(Example);
export { Example };

注意,在3.x.x中,<Link>组件本身使用router.push,因此您可以传递任何传递<Linkto=标记的内容,例如:

   this.props.router.push({pathname: '/some/path', query: {key1: 'val1', key2: 'val2'})'

React路由器V4

如果您使用的是版本4,那么您可以使用我的库(无耻的插件),在那里您只需发送一个操作,一切都正常!

dispatch(navigateTo("/aboutUs"));

脱扣器