实际开发中,React应用常见问题【持续更新中】
实际开发中,React应用常见问题【持续更新中】
一、路由相关
"react-router-dom": "^6.14.2", "react": "^18.2.0",
1、监听路由
ts
import { useLocation } from 'react-router-dom'
export default function AppHeader() {
const [selectMenu, setSelectMenu] = useState<string>('')
const location = useLocation()
useEffect(() => {
// location: 页面刷新 和 路径变化【触发路由】 都会监听到
// 解决页面刷新或者是用户手动输入路径时, 路径和menu选中状态不匹配的问题
setSelectMenu(location.pathname)
}, [location])
return <>test</>
}
2、路由编程式导航
useNavigate()
ts
import { useNavigate } from 'react-router-dom'
export default function AppHeader() {
const navigate = useNavigate()
const toOtherPageByPath = () => {
// 未携带参数的编程式导航
navigate(路由path)
}
return (
<>
<button onClick={toOtherPageByPath}>test</button>
</>
)
3、路由链接导航
ts
import { Link } from 'react-router-dom'
<Link to={'路径'}>Back Home</Link>