页面加载后未恢复react-router-dom中最后访问的url路径/页面,并期望在页面加载后恢复最后访问的url路径
Nav.js
import React from 'react'
import { Link, useLocation } from 'react-router-dom'
const NavLinks = props => {
const pathname = useLocation().pathname
return (
<nav>
<ul className={classes.navlinks}>
<li>
<Link
className={`${pathname === '/home' ? classes.active : classes.link}`}
to='/home'
onClick={handlePath}
>
{width > 1150 ? 'Home' : ''}
<Tooltip {...{
placement: 'bottom',
title: 'Home'
}}>
<Badge>
<IconButton style={{padding: '2px'}}>
<TrendingUpOutlinedIcon />
</IconButton>
</Badge>
</Tooltip>
</Link>
</li>
<li>
<Link
className={`${pathname === '/about' ? classes.active : classes.link}`}
to='/about'
onClick={handlePath}
>
{width > 1150 ? 'About' : ''}
<Tooltip {...{
placement: 'bottom',
title: 'About'
}}>
<Badge>
<IconButton style={{padding: '2px'}}>
<ConfirmationNumberOutlinedIcon />
</IconButton>
</Badge>
</Tooltip>
</Link>
</li>
</ul>
</nav>
)
}
我使用了一些逻辑以以下方式实现相同的目标
步骤1:当用户点击导航按钮时,我们需要将路径存储在本地存储
步骤2:页面重新加载后需要从localstorage获取最后访问的路径名,并使用useEffect和history对象以以下方式恢复之前的路径
import React from 'react'
import { Link, useLocation, useHistory } from 'react-router-dom'
const NavLinks = props => {
const pathname = useLocation().pathname
const history = useHistory()
const [ navChanged, setNavChanged ] = React.useState(false)
const handlePath = React.useCallback(() => {
setNavChanged(true)
}, [ ])
React.useEffect(() => {
if (navChanged) {
localStorage.setItem('path', pathname)
}
})
React.useEffect(() => {
history.push(localStorage.getItem('path') || 'home')
}, [])
return (
<nav>
<ul className={classes.navlinks}>
<li>
<Link
className={`${pathname === '/home' ? classes.active : classes.link}`}
to='/home'
onClick={handlePath}
>
{width > 1150 ? 'Home' : ''}
<Tooltip {...{
placement: 'bottom',
title: 'Home'
}}>
<Badge>
<IconButton style={{padding: '2px'}}>
<TrendingUpOutlinedIcon />
</IconButton>
</Badge>
</Tooltip>
</Link>
</li>
<li>
<Link
className={`${pathname === '/about' ? classes.active : classes.link}`}
to='/about'
onClick={handlePath}
>
{width > 1150 ? 'About' : ''}
<Tooltip {...{
placement: 'bottom',
title: 'About'
}}>
<Badge>
<IconButton style={{padding: '2px'}}>
<ConfirmationNumberOutlinedIcon />
</IconButton>
</Badge>
</Tooltip>
</Link>
</li>
</ul>
</nav>
)
}