Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
504 views
in Technique[技术] by (71.8m points)

reactjs - 使用React Router以编程方式导航(Programmatically navigate using react router)

With react-router I can use the Link element to create links that are natively handled by react router. (通过react-router我可以使用Link元素来创建由react路由器本地处理的链接。)

I see internally it calls this.context.transitionTo(...) . (我在内部看到它调用this.context.transitionTo(...) 。)

I want to do a navigation, but not from a link, from a dropdown selection for example. (我想从下拉列表中进行导航,而不是从链接进行导航。) How can I do this in code? (如何在代码中执行此操作?) What is this.context ? (这是什么this.context ?)

I saw the Navigation mixin, but can I do this without mixins? (我看到了Navigation混合器,但是没有混合器可以做到吗?)

  ask by George Mauer translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

React Router v5.1.0 with hooks (带有钩子的React Router v5.1.0)

There is a new useHistory hook in React Router >5.1.0 if you are using React >16.8.0 and functional components. (如果您使用React> 16.8.0和功能组件,则在React Router> 5.1.0中有一个新的useHistory挂钩。)

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

function HomeButton() {
  let history = useHistory();

  function handleClick() {
    history.push("/home");
  }

  return (
    <button type="button" onClick={handleClick}>
      Go home
    </button>
  );
}

React Router v4 (反应路由器v4)

With v4 of React Router, there are three approaches that you can take to programmatic routing within components. (使用React Router v4,您可以采用三种方法在组件内进行编程路由。)

  1. Use the withRouter higher-order component. (使用withRouter高阶组件。)
  2. Use composition and render a <Route> (使用合成并渲染<Route>)
  3. Use the context . (使用context 。)

React Router is mostly a wrapper around the history library. (React Router主要是history库的包装器。) history handles interaction with the browser's window.history for you with its browser and hash histories. (history处理与浏览器window.history 。交互的history ,以及浏览器和哈希历史记录。) It also provides a memory history which is useful for environments that don't have a global history. (它还提供了内存历史记录,这对于没有全局历史记录的环境很有用。) This is particularly useful in mobile app development ( react-native ) and unit testing with Node. (这在使用Node进行移动应用程序开发( react-native )和单元测试中特别有用。)

A history instance has two methods for navigating: push and replace . (history实例有两种导航方法: pushreplace 。) If you think of the history as an array of visited locations, push will add a new location to the array and replace will replace the current location in the array with the new one. (如果您将history视为访问过的位置数组,则push将向该位置添加新位置,而replace将用新位置replace该数组中的当前位置。) Typically you will want to use the push method when you are navigating. (通常,您在导航时会希望使用push方法。)

In earlier versions of React Router, you had to create your own history instance, but in v4 the <BrowserRouter> , <HashRouter> , and <MemoryRouter> components will create a browser, hash, and memory instances for you. (在早期版本的React Router中,您必须创建自己的history实例,但是在v4中, <BrowserRouter><HashRouter><MemoryRouter>组件将为您创建浏览器,哈希和内存实例。) React Router makes the properties and methods of the history instance associated with your router available through the context, under the router object. (React Router通过router对象下的上下文使与路由器关联的history实例的属性和方法可用。)

1. Use the withRouter higher-order component (1.使用withRouter高阶组件)

The withRouter higher-order component will inject the history object as a prop of the component. (withRouter高阶组件将注入history对象作为该组件的支持。) This allows you to access the push and replace methods without having to deal with the context . (这使您无需处理context即可访问pushreplace方法。)

import { withRouter } from 'react-router-dom'
// this also works with react-router-native

const Button = withRouter(({ history }) => (
  <button
    type='button'
    onClick={() => { history.push('/new-location') }}
  >
    Click Me!
  </button>
))

2. Use composition and render a <Route> (2.使用合成并渲染<Route>)

The <Route> component isn't just for matching locations. (<Route>组件不仅用于匹配位置。) You can render a pathless route and it will always match the current location . (您可以渲染无路径的路线, 它将始终与当前位置匹配 。) The <Route> component passes the same props as withRouter , so you will be able to access the history methods through the history prop. (<Route>组件传递与withRouter相同的道具,因此您将能够通过history道具访问history方法。)

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

const Button = () => (
  <Route render={({ history}) => (
    <button
      type='button'
      onClick={() => { history.push('/new-location') }}
    >
      Click Me!
    </button>
  )} />
)

3. Use the context* (3.使用上下文*)

But you probably should not (但是你可能不应该)

The last option is one that you should only use if you feel comfortable working with React's context model. (最后一个选项是只有在您熟悉使用React的上下文模型时才应使用的选项。) Although context is an option, it should be stressed that context is an unstable API and React has a section Why Not To Use Context in their documentation. (尽管上下文是一个选项,但应该强调的是上下文是不稳定的API,React在其文档中有“ 为什么不使用上下文”一节。) So use at your own risk! (因此,使用后果自负!)

const Button = (props, context) => (
  <button
    type='button'
    onClick={() => {
      // context.history.push === history.push
      context.history.push('/new-location')
    }}
  >
    Click Me!
  </button>
)

// you need to specify the context type so that it
// is available within the component
Button.contextTypes = {
  history: React.PropTypes.shape({
    push: React.PropTypes.func.isRequired
  })
}

1 and 2 are the simplest choices to implement, so for most use cases, they are your best bets. (1和2是最简单的实现方式,因此对于大多数用例来说,它们是最好的选择。)


In addition you can get more knowledge from below links about the Routing, URL Parameters and Nested routing. (此外,您可以从以下链接中获得有关路由,URL参数和嵌套路由的更多知识。)

Routing in React JS (在React JS中路由)
- Step by step explaination of how to integrate the react-router in ReactJS (-逐步说明如何在ReactJS中集成react-router)

URL Parameters with React Router (使用React Router的URL参数)
- Here you can get the idea about how to set URL parameters with React Router. (-在这里您可以了解如何使用React Router设置URL参数。) Major use of URL parameters routing is to render the same component based on its dynamic url. (URL参数路由的主要用途是根据其动态URL呈现相同的组件。)

Nested Routes in React JS (React JS中的嵌套路由)
- If you want to load sub routes in main routes then you have to create a nested routes. (-如果要在主路径中加载子路径,则必须创建嵌套路径。) Here is the live example of it. (这是它的现场示例。)

在此处输入图片说明

Hope this will help you! (希望能帮到你!)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...