栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

使用React Router以编程方式导航

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用React Router以编程方式导航

带有钩子的React Router v5.1.0

useHistory
如果您使用React> 16.8.0和功能组件,则React Router> 5.1.0中会有一个新的钩子。

import { useHistory } from "react-router-dom";function HomeButton() {  const history = useHistory();  function handleClick() {    history.push("/home");  }  return (    <button type="button" onClick={handleClick}>      Go home    </button>  );}

反应路由器v4

使用React Router v4,您可以采用三种方法在组件内进行编程路由。

  1. 使用
    withRouter
    高阶组件。
  2. 使用合成并渲染
    <Route>
  3. 使用
    context

React
Router主要是

history
库的包装器。
history
通过浏览
window.history
器和哈希历史记录为您处理与浏览器的交互。它还提供了内存历史记录,这对于没有全局历史记录的环境很有用。这在移动应用程序开发(
react-native
)和使用Node进行单元测试中特别有用。

一个

history
实例有用于导航两种方法:
push
replace
。如果您将
history
视为已访问位置的数组,
push
则将一个新位置添加到该数组中,
replace
并将该数组中的当前位置替换为新位置。通常,您将
push
在导航时使用该方法。

在早期版本的阵营路由器,你必须创建自己的

history
实例,但在第4版的
<BrowserRouter>
<HashRouter>
<MemoryRouter>
组件将创建一个浏览器,哈希和内存的实例为您服务。React
Router
history
通过
router
对象下的上下文使与路由器关联的实例的属性和方法可用。

1.使用
withRouter
高阶成分

withRouter
高次成分将注入的
history
对象作为所述部件的支柱。这样一来,您无需处理即可访问
push
replace
方法
context

import { withRouter } from 'react-router-dom'// this also works with react-router-nativeconst Button = withRouter(({ history }) => (  <button    type='button'    onClick={() => { history.push('/new-location') }}  >    Click Me!  </button>))

2.使用合成并渲染
<Route>

<Route>
组件不仅用于匹配位置。您可以渲染无路径路线,并且 路线 将始终与当前位置匹配
。该
<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.使用上下文*

但是你可能不应该

最后一个选项是只有在您熟悉使用React的上下文模型时才应使用的选项(React的Context
API从v16开始是稳定的)。

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 componentButton.contextTypes = {  history: React.PropTypes.shape({    push: React.PropTypes.func.isRequired  })}

1和2是最简单的实现方法,因此对于大多数用例来说,它们是最好的选择。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/448862.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号