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

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

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

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


当前回答

如果您使用的是更新版本的React,那么使用“useHistory”钩子是最好的选择。

其他回答

您还可以在无状态组件中使用useHistory钩子。文档示例:

import { useHistory } from "react-router"

function HomeButton() {
  const history = useHistory()

  return (
    <button type="button" onClick={() => history.push("/home")}>
      Go home
    </button>
  )
}

注意:在中添加了挂钩react-router@5.1.0并且需要反应@>=16.8

React路由器v4和ES6

您可以使用Router和this.props.history.push。

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

class Home extends Component {

    componentDidMount() {
        this.props.history.push('/redirect-to');
    }
}

export default withRouter(Home);

只需使用useNavigate from react router dom

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

const MYComponent = () => {
    const navigate = useNavigate();

    navigate("Xyz/MYRoutes");

 
}

export default MYComponent;

在代码中使用上述的useNavigate功能。

试试React Hook Router,“反应路由器的现代替代品”:

import { useRoutes, usePath, A} from "hookrouter";

要回答OP关于通过选择框链接的问题,您可以这样做:

navigate('/about');

更新的答案

我认为React Hook Router是一个很好的入门套件,帮助我学习了路由,但我后来更新了React Router,了解了它的历史和查询参数处理。

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


const Component = (props) => {
    const history = useHistory();

    // Programmatically navigate
    history.push(newUrlString);
}

您可以将要导航到的位置推到历史位置。

如果您碰巧通过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组件可能会更好。