使用反应路由器V4进行编程导航 [英] Programmatically navigate using react router V4

查看:106
本文介绍了使用反应路由器V4进行编程导航的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚从v3替换为$ code> react-router 。

但我不知道如何以编程方式导航成员函数元器件
ie handleClick()函数在处理一些后,我想导航到 / path / some / where 数据。
我曾经通过

I have just replaced react-router from v3 to v4.
But I am not sure how to programmatically navigate in the member function of a Component. i.e in handleClick() function I want to navigate to /path/some/where after processing some data. I used to do that by

import {browserHistory}从'react-router'
browserHistory.push('/ path / some / where');

但是在v4中找不到这样的界面。

如何使用v4导航?

But I can't find such interfaces in v4.
How can I navigate using v4?

推荐答案

如果您定位浏览器环境,则需要使用 react-router-dom 包,而不是反应路由器。它们遵循与React相同的方法,以分离核心(反应)和平台特定代码( react-dom react-native )与您不需要安装两个单独的软件包的微妙区别,因此环境软件包包含您需要的一切。您可以将其添加到您的项目中:

If you are targeting browser environments, you need to use react-router-dom package, instead of react-router. They are following the same approach as React did, in order to separate the core, (react) and the platform specific code, (react-dom, react-native ) with the subtle difference that you don't need to install two separate packages, so the environment packages contain everything you need. You can add it to your project as:

yarn add react-router-dom

npm i -S react-router-dom

您需要做的第一件事是提供一个< BrowserRouter> 作为应用程序中最顶层的父组件。 < BrowserRouter> 使用HTML5 历史记录 API并为您管理,因此您不必担心将其自动实例化,并将其传递给< BrowserRouter> 组件作为支柱(如以前版本中所需)。

The first thing you need to do is to provide a <BrowserRouter> as the top most parent component in your application. <BrowserRouter> uses the HTML5 history API and manages it for you, so you don't have to worry about instantiating it yourself and passing it down to the <BrowserRouter> component as a prop (as you needed to do in previous versions).

在V4中,为了以编程方式导航,您需要访问历史记录对象,可通过React 上下文,只要您有一个< BrowserRouter> 提供者组件作为最多的父你的申请。该库通过上下文暴露了路由器对象,该对象本身包含历史作为属性。 历史界面提供了几种导航方法,例如 push replace goBack 等。您可以查看属性和方法的全部列表此处

In V4, for navigating programatically you need to access the history object, which is available through React context, as long as you have a <BrowserRouter> provider component as the top most parent in your application. The library exposes through context the router object, that itself contains history as a property. The history interface offers several navigation methods, such as push, replace and goBack, among others. You can check the whole list of properties and methods here.

Redux / Mobx用户的重要注意事项


如果您使用redux或mobx作为您的州政府管理库在您的应用程序中,您可能会遇到触发URL更新后未重新呈现的组件位置感知问题

发生这种情况是因为<$使用上下文模型将c $ c> react-router 将位置传递给组件。

That's happening because react-router passes location to components using the context model.


连接和观察器都创建组件,其shouldComponentUpdate方法对当前道具和他们的下一个道具做了较浅的比较。这些组件只有在至少一个支柱已经改变时才会重新渲染。这意味着为了确保在位置更改时更新它们,需要在位置更改时给予更改的支持。

Both connect and observer create components whose shouldComponentUpdate methods do a shallow comparison of their current props and their next props. Those components will only re-render when at least one prop has changed. This means that in order to ensure they update when the location changes, they will need to be given a prop that changes when the location changes.

解决这个问题的两种方法是:

The 2 approaches for solving this are:


  • 连接的组件包在无路径< Route /> 。当前的位置对象是< Route> 传递给它呈现的组件的道具之一

  • 连接的组件与 withRouter 更高级的组件包装,实际上具有相同的效果并注入位置作为支柱

  • Wrap your connected component in a pathless <Route />. The current location object is one of the props that a <Route> passes to the component it renders
  • Wrap your connected component with the withRouter higher-order component, that in fact has the same effect and injects location as a prop

除此之外,有四种方式可以编程按照建议进行排序:

Setting that aside, there are four ways to navigate programatically, ordered by recommendation:

1.-使用< Route> / h3> 它促进声明式样式。在v4之前,< Route /> 组件放置在组件层次结构的顶部,必须事先考虑您的路由结构。但是,现在,您可以在树中使用< Route> 组件任何地方,这样您可以根据URL进行有条件的渲染。 路线注入匹配位置历史作为道具进入您的组件。导航方法(例如 push 替换 goBack ...)可用作历史对象的属性。

1.- Using a <Route> Component

It promotes a declarative style. Prior to v4, <Route /> components were placed at the top of your component hierarchy, having to think of your routes structure beforehand. However, now you can have <Route> components anywhere in your tree, allowing you to have a finer control for conditionally rendering depending on the URL. Route injects match, location and history as props into your component. The navigation methods (such as push, replace, goBack...) are available as properties of the history object.

有3种方法可以使用路由,使用组件 render children 道具,但不要在同一个 Route 中使用多个。选择取决于用例,但是如果路径与url位置匹配,则前两个选项将仅渲染您的组件,而 children 将渲染组件是否与该位置匹配(适用于根据URL匹配调整UI)。

There are 3 ways to render something with a Route, by using either component, render or children props, but don't use more than one in the same Route. The choice depends on the use case, but basically the first two options will only render your component if the path matches the url location, whereas with children the component will be rendered whether the path matches the location or not (useful for adjusting the UI based on URL matching).

如果您要自定义您的组件渲染输出,您需要将组件包装在一个函数中,并使用 render 选项,以便传递给您的组件任何其他匹配位置历史 。一个例子来说明:

If you want to customise your component rendering output, you need to wrap your component in a function and use the render option, in order to pass to your component any other props you desire, apart from match, location and history. An example to illustrate:

import { BrowserRouter as Router } from 'react-router-dom'

const ButtonToNavigate = ({ title, history }) => (
  <button
    type="button"
    onClick={() => history.push('/my-new-location')}
  >
    {title}
  </button>
);

const SomeComponent = () => (
  <Route path="/" render={(props) => <ButtonToNavigate {...props} title="Navigate elsewhere" />} />
)    

const App = () => (
  <Router>
    <SomeComponent /> // Notice how in v4 we can have any other component interleaved
    <AnotherComponent />
  </Router>
);

2.-使用 withRouter HoC

这个更高阶的组件将注入与 Route 。但是,它带有一个限制:每个文件只能有一个HoC。

This higher order component will inject the same props as Route. However, it carries along the limitation that you can have only 1 HoC per file.

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

const ButtonToNavigate = ({ history }) => (
  <button
    type="button"
    onClick={() => history.push('/my-new-location')}
  >
    Navigate
  </button>
);


ButtonToNavigate.propTypes = {
  history: React.PropTypes.shape({
    push: React.PropTypes.func.isRequired,
  }).isRequired,
};

export default withRouter(ButtonToNavigate);

3.-使用重定向组件

呈现<重定向> 将导航到新位置。但请注意,默认情况下 ,当前位置被新的位置替换为服务器端重定向(HTTP 3xx)。新位置由提供给 prop,可以是一个字符串(要重定向到的URL)或位置对象。如果您想要将新条目推入历史记录,请传递 push prop,并将其设置为 true

3.- Using a Redirect component

Rendering a <Redirect> will navigate to a new location. But keep in mind that, by default, the current location is replaced by the new one, like server-side redirects (HTTP 3xx). The new location is provided by to prop, that can be a string (URL to redirect to) or a location object. If you want to push a new entry onto the history instead, pass a push prop as well and set it to true

<Redirect to="/your-new-location" push />

4.-访问路由器手动通过上下文

有点不鼓励,因为上下文仍然是一个实验性API并且可能会在将来的React版本中破坏/更改

4.- Accessing router manually through context

A bit discouraged because context is still an experimental API and it is likely to break/change in future releases of React

const ButtonToNavigate = (props, context) => (
  <button
    type="button"
    onClick={() => context.router.history.push('/my-new-location')}
  >
    Navigate to a new location
  </button>
);

ButtonToNavigate.contextTypes = {
  router: React.PropTypes.shape({
    history: React.PropTypes.object.isRequired,
  }),
};

不用说,还有其他的路由器组件是用于非浏览器生态系统的,如< NativeRouter> ,它复制内存中的导航堆栈,并定位到React Native平台,可通过 react-router-native 包。

Needless to say there are also other Router components that are meant to be for non browser ecosystems, such as <NativeRouter> that replicates a navigation stack in memory and targets React Native platform, available through react-router-native package.

如需进一步的参考,请不要犹豫,看看官方文档。还有一个由图书馆合作者之一制作的视频,它提供反应路由器v4很酷的介绍,突出显示了一些主要的变化。

For any further reference, don't hesitate to take a look at the official docs. There is also a video made by one of the co-authors of the library that provides a pretty cool introduction to react-router v4, highlighting some of the major changes.

这篇关于使用反应路由器V4进行编程导航的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆