[React] Keep Application State in Sync with Browser History
React in with application State history Sync keep
2023-09-14 09:00:52 时间
Using pushState and passing route data via context allows our application to respond to route changes made from Link components, but using the back and forward buttons in the browser doesn’t update the application state as we would expect. In this lesson, we’ll add event handling to our Router component to handle history popState events so routing behavior is maintained for the back and forward buttons.
import React, {Component} from 'react'; const getCurrentPath = () => { const path = document.location.pathname; return path.substring(path.lastIndexOf('/')); }; export class Router extends Component { state = { route: getCurrentPath() }; handleLinkClick = (route) => { this.setState({route}); history.pushState(null, '', route); }; static childContextTypes = { route: React.PropTypes.string, linkHandler: React.PropTypes.func }; getChildContext() { return { route: this.state.route, linkHandler: this.handleLinkClick }; } render() { return ( <div>{this.props.children}</div> ); } componentDidMount() { window.onpopstate = () => { this.setState({route: getCurrentPath()}) } }
相关文章
- react源码解析3.react源码架构
- 07-React Hooks(路由组件懒加载, Context上下文, 组件优化...)
- react源码中的生命周期和事件系统
- React强制刷新组件的一种方式
- 高频react面试题自检
- react的jsx和React.createElement是什么关系?面试常问_2023-02-27
- 从源码角度看React-Hydrate原理_2023-03-01
- react源码分析context
- React组件复用的技巧详解
- 深入react源码中的setState
- Jest:给你的 React 项目加上单元测试
- 在React当中使用scss和按需加载antd
- react源码解析-开篇介绍和面试题
- React源码分析2-深入理解fiber5
- Oracle游标IN模式使用指南(oracle游标in)
- Oracle中使用EXISTS代替IN(oracle替换in)
- Oracle中IN操作符的用法(oracle中in的用法)
- 子查询MySQL联表IN子查询:实现跨表快速查询(mysql联表in)
- 利用Oracle中IN函数进行数据查询(oracle带in函数)
- 语句SQL Server中使用IN语句处理多值查询(sqlserver中in)
- 使用in操作符时MySQL是否能够充分利用索引MySQL In操作符优化技巧(mysql中in走索引吗)
- MySQL中的IN子句如何利用索引实现高效查询(mysql中in使用索引)
- 深入探究Mysql中IN与AND逻辑运算的应用(mysql中in与and)
- 解决MySQL中IN不走索引问题的方法(mysql中in不走索引)
- 以Oracle IN查询精准定位你要的信息(oracle使用in查询)