React V6 编程式路由导航 useNavigate()要用函数式组件否则Hook报错
首先const navigate = useNavigate();则可以使用navigate这个函数代替this.history.push、this.history.replace、this.history.gofoward、this.history.goback、this.history.go1.注意:navigete默认history的是push模式,使用replace模式需要添加{repla
·
首先const navigate = useNavigate();
则可以使用navigate这个函数代替this.history.push、this.history.replace、this.history.gofoward、this.history.goback、this.history.go
1.注意:navigete默认history的是push模式,使用replace模式需要添加
{replace:true} //开启replace模式
2.注意:使用useNavigate()必须是在函数式组件中
一开始用在类式组件中,报错:
react-dom.development.js:14906 Uncaught Error: Invalid hook call.
Hooks can only be called inside of the body of a function component.
This could happen for one of the following reasons:
- You might have mismatching versions of React and the renderer (such as React DOM)
- You might be breaking the Rules of Hooks
- You might have more than one copy of React in the same app
完整代码:
(以params接收参数为例)
src/pages/Home/Message:
import React, { Component } from 'react'
import { Link, Route, Routes, useParams, useNavigate } from 'react-router-dom'
import Detail from './Detail'
const state = {
messageArr: [
{ id: '01', title: 'message1' },
{ id: '02', title: 'message2' },
{ id: '03', title: 'message3' },
]
}
const Message = () => {
const { messageArr } = state
const navigate = useNavigate();
//push跳转 以params参数为例,navigate默认开启push模式
const pushShow = (id, title) => {
navigate(`/home/message/detail/${id}/${title}`)
}
//replace跳转 以params参数为例,开启replace:true
const replaceShow = (id, title) => {
navigate(`/home/message/detail/${id}/${title}`, { replace: true })
}
//前进
const forward = () => {
navigate(1)
}
//前进
const back = () => {
navigate(-1)
}
//go
//前进
const go = () => {
navigate(2)
}
return (
<div>
<ul>
{
messageArr.map((msgObj) => {
return (
<li key={msgObj.id}>
{/* 向路由组件传递params参数 */}
<Link to={`/home/message/detail/${msgObj.id}/${msgObj.title}`}>{msgObj.title}</Link>
<button onClick={() => { pushShow(msgObj.id, msgObj.title) }}>push</button>
<button onClick={() => { replaceShow(msgObj.id, msgObj.title) }}>replace</button>
</li>
)
})
}
</ul>
<hr />
<Routes>
{/* 声明接收params参数 */}
<Route path="/detail/:id/:title" element={<Detail />} />
</Routes>
<button onClick={forward}>前进</button>
<button onClick={back}>后退</button>
<button onClick={go}>go</button>
</div>
)
}
export default Message
更多推荐
已为社区贡献1条内容
所有评论(0)