注意:父子组件都必须是函数式组件
// 父组件 Message
import React from 'react'
import { Link, Route, Routes, useNavigate } from 'react-router-dom'
import { Detail } from './Detail'
export const Message = () => {
const list = [
{ id: '001', title: '消息1' },
{ id: '002', title: '消息2' },
{ id: '003', title: '消息3' }
]
const navigate = useNavigate()
function replaceShow(id, title) {
// replace + params
// navigate(`/home/message/detail/${id}/${title}`,{replace:true})
// replace + query
// navigate(`/home/message/detail?id=${id}&title=${title}`, { replace: true })
// replace + state
navigate(`/home/message/detail`, { replace: true, state: { id, title } })
}
function pushShow(id, title) {
// replace + params
// navigate(`/home/message/detail/${id}/${title}`,{replace:false})
// replace + query
// navigate(`/home/message/detail?id=${id}&title=${title}`, { replace: false })
// replace + state
navigate(`/home/message/detail`, { replace: false, state: { id, title } })
}
function goForwad(){
navigate(1)
}
function goBack(){
navigate(-1)
}
return (
<div>
<ul>
{
list.map(i => (
<li key={i.id}>
<Link to={`/home/message/detail/${i.id}/${i.title}`}>{i.title}</Link>
<button onClick={() => { replaceShow(i.id, i.title) }}>replace</button>
<button onClick={() => { pushShow(i.id, i.title) }} >push</button>
</li>
))
}
</ul>
<hr />
<button onClick={goForwad}>前进</button>
<button onClick={goBack}>后退</button>
<Routes>
<Route path='/detail/' element={<Detail />}></Route>
{/* <Route path="*" element={<Navigate to="/home/message/detail" state={{id:this.state.list[0].id,title:this.state.list[0].title}}/>}></Route> */}
</Routes>
</div>
)
}
// 子组件Detail
import React from 'react'
import { useParams,useSearchParams,useLocation } from 'react-router-dom'
export const Detail = () => {
const [data,setState] = React.useState([
{ id: '001', content: '你好,中国' },
{ id: '002', content: '你好,未来' },
{ id: '003', content: '你好,小彭' }
])
// const params = useParams()
// const [params] = useSearchParams()
const {state:{id,title}} = useLocation()
return (
<div>
<ul>
<li>ID:{id}</li>
<li>TITLE:{title}</li>
<li>CONTENT:{data.find(i => i.id === id).content}</li>
</ul>
</div>
)
}
|