一、react模拟hash路由的实现
原理:hash路由的原理是监听hashchange事件
import { useEffect, useState } from 'react'
function App() {
let [curHash, setCurHash] = useState('')
useEffect(() => {
function onChange() {
setCurHash(window.location.hash.slice(1))
}
onChange()
window.addEventListener('hashchange', onChange)
return () => {
window.removeEventListener('hashchange', onChange)
}
}, [])
return (<>
<h1>react模拟hash路由的实现</h1>
<ul>
<li>
<a href="#/home">首页</a>
</li>
<li>
<a href="#/news">新闻页</a>
</li>
<li>
<a href="#/seach">搜索页</a>
</li>
</ul>
{renderList(curHash)}
</>)
}
function renderList(curHash) {
switch (curHash) {
case '/home':
return <Home />
case '/news':
return <News />
case '/seach':
return <Seach />
default:
return <NotFound />
}
}
let Home = () => <> <h1>首页/home</h1> </>
let News = () => <><h1>新闻页/news </h1></>
let Seach = () => <><h1>首页/seach</h1></>
let NotFound= ()=><> <h1>404</h1></>
export default App