react 项目学习笔记一(react-router中的history)

本文介绍了react-router中的history管理,包括createHashHistory、createBrowserHistory和createMemoryHistory三种类型。createHashHistory适用于服务器无需配置的场景,但不推荐在生产环境中使用;createBrowserHistory是推荐的浏览器历史管理方式,利用History API操作真实URL;createMemoryHistory主要用于测试和服务器渲染,不涉及地址栏变化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

react-router 中的history

eact-router 是建立在history之上的

history 一个管理js应用session会话历史的js库。它将不同环境(浏览器,node...)的变量统一成了一个简易的API来管理历史堆栈、导航、确认跳转、以及sessions间的持续状态。


//基本 使用
import { createHistory } from 'history'

const history = createHistory()

// 当前的地址
const location = history.getCurrentLocation()

// 监听当前的地址变换
const unlisten = history.listen(location => {
  console.log(location.pathname)
})

// 将新入口放入历史堆栈
history.push({
  pathname: '/the/path',
  search: '?a=query',

  // 一些不存在url参数上面的当前url的状态值
  state: { the: 'state' }
})

// When you're finished, stop the listener
unlisten()

你也可以使用 history对象来的方法来改变当前的location:

  • push(location)
  • replace(location)
  • go(n)
  • goBack()
  • goForward()

一个 history 知道如何去监听浏览器地址栏的变化, 并解析这个 URL 转化为 location 对象, 然后 router 使用它匹配到路由,最后正确地渲染对应的组件。

location对象包括:

pathname      同window.location.pathname
search        同window.location.search
state         一个捆绑在这个地址上的object对象
action        PUSH, REPLACE, 或者 POP中的一个
key           唯一ID
常用的三种history
// HTML5 history, 推荐
import createHistory from 'history/lib/createBrowserHistory'

// Hash history
import createHistory from 'history/lib/createHashHistory'

// 内存 history (如:node环境)
import createHistory from 'history/lib/createMemoryHistory'

createHashHistory

这是一个你会获取到的默认 history ,如果你不指定某个 history (即 <Router>{/* your routes */}</Router>)。它用到的是 URL 中的 hash(#)部分去创建形如 http://example.com/#/some/path 的路由。

Hash history 是默认的,因为它可以在服务器中不作任何配置就可以运行,并且它在全部常用的浏览器包括 IE8+ 都可以用。但是我们不推荐在实际生产中用到它,因为每一个 web 应用都应该有目的地去使用createBrowserHistory。

createBrowserHistory

Browser history 是由 React Router 创建浏览器应用推荐的 history。它使用 History API 在浏览器中被创建用于处理 URL,新建一个像这样真实的`URL example.com/some/path`

createMemoryHistory

Memory history 不会在地址栏被操作或读取。这就解释了我们是如何实现服务器渲染的。同时它也非常适合测试和其他的渲染环境(像 React Native )。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值