react路由原理解析

原理: 在dom渲染完成之后,给window 添加   “hashchange” 事件监听页面hash的变化,并且在state属性之中添加了 route属性,代表当前页面的路由。

1、当点击连接  页面hash改变时,触发绑定在window 上的  hashchange 事件,

2、在 hashchange 事件中改变组件的 state中的 route 属性,(react组件的state属性改变时,自动重新渲染页面)

3、页面 随着 state 中的route属性改变自动 根据  不停的hash  给  Child  变量赋值不通的组件,进行渲染

核心代码:


import React from 'react'
import { render } from 'react-dom'



const About = function () {
return < div>111div>
}
const Inbox = function () {
return < div>222div>
}
const Home = function () {
return < div>333div>
}

class App extends React. Component {

state = {
route: window.location.hash. substr( 1)
}

componentDidMount() {
window. addEventListener( 'hashchange', () => {
this. setState({
route: window.location.hash. substr( 1)
})
})
}

render() {
let Child
switch ( this.state.route) {
case '/about': Child = About; break;
case '/inbox': Child = Inbox; break;
default: Child = Home;
}

return (
< div>
< h1>Apph1>
< ul>
< li>< a href = "#/about">Abouta>li>
< li>< a href = "#/inbox">Inboxa>li>
ul>
< Child />
div>
)
}
}

render(< App />, document.body)

你可能感兴趣的:(前端学习笔记)