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

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

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

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


当前回答

上面已经提到,我们可以使用useNavigate()在上一次更新React Router V6(不包括useHistory)中导航

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

const myComponent = () => {
  const navigate = useNavigate();
  navigate('my_url');
  ...
}

但我在这里找不到的是调用导航出React组件,就像将redux saga函数中的页面导航到另一个页面。以防万一,如果你有同样的问题,这是我发现的。

在根组件中(我称之为<App/>)

import { useNavigate } from 'react-router-dom';
import useBus from 'use-bus';

const App = () => {
  const navigate = useNavigate();
  useBus('@@ui/navigate', (action) => navigate(action.payload.url), []);
  ...
}

脱离React组件(在我的例子中是redux saga函数)

import { dispatch } from 'use-bus';

dispatch({ type: '@@ui/navigate', payload: { url: '/404' } });

希望有帮助!

其他回答

这可能不是最好的方法,但。。。使用react router v4,下面的TypeScript代码可以为一些人提供一些想法。

在下面的渲染组件(例如LoginPage)中,可以访问router对象,只需调用router.transitionTo('/home')即可导航。

导航代码取自。

“react router”:“^4.0.0-2”,“反应”:“^15.3.1”,

从“react Router/BrowserRouter”导入路由器;从“react History/BrowserHistory”导入{History};从“history/createBrowserHistory”导入createHistory;consthistory=createHistory();接口MatchWithPropsInterface{component:React.component的类型,router:路由器,历史:历史,确切地?:任何图案:字符串}类MatchWithProps扩展React.Component<MatchWithPropsInterface,any>{render(){返回(<Match{…this.props}render={(matchProps)=>(React.createElement(this.props.component,this.props))}/>)}}ReactDOM.渲染(<路由器>{({路由器})=>(<div><MatchWithProps justly pattern=“/”component={LoginPage}router={router}history={history}/><MatchWithProps pattern=“/login”component={LoginPage}router={router}history={history}/><MatchWithProps pattern=“/home”component={homepage}router={router}history={history}/><缺少组件={NotFoundView}/></div>)}</路由器>,document.getElementById('app'));

随着React Router v4即将推出,现在有了一种新的实现方式。

import { MemoryRouter, BrowserRouter } from 'react-router';

const navigator = global && global.navigator && global.navigator.userAgent;
const hasWindow = typeof window !== 'undefined';
const isBrowser = typeof navigator !== 'undefined' && navigator.indexOf('Node.js') === -1;
const Router = isBrowser ? BrowserRouter : MemoryRouter;

<Router location="/page-to-go-to"/>

react lego是一个示例应用程序,展示了如何使用/更新react router,它包括导航应用程序的示例功能测试。

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

以下是最简单、最干净的方法,大约是当前的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'})'

在写作时,正确的答案适合我

this.context.router.history.push('/');

但您需要将PropTypes添加到组件中

Header.contextTypes = {
  router: PropTypes.object.isRequired
}
export default Header;

不要忘记导入PropTypes

import PropTypes from 'prop-types';