文章目录
- 1、routes.js
- 2、Message.jsx
- 3、Detail.jsx
- 4、Result
- 5、另外一个可以获取 search 的新 Hook :useLocation
项目修改自 上一节 的 Demo
1、routes.js
import { Navigate } from 'react-router-dom'
import About from '../components/About'
import Home from '../components/Home'
import Message from '../components/Home/Message'
import News from '../components/Home/News'
import Detail from '../components/Home/Message/Detail'
const routes = [{
path: '/about',
element: <About />
}, {
path: '/home',
element: <Home />,
children: [{
path: 'news',
element: <News />
}, {
path: 'message',
element: <Message />,
children: [{
path: 'detail',
element: <Detail />
}]
}]
}, {
path: '/',
element: <Navigate to='/about' />
}]
export default routes
2、Message.jsx
import React, { useState } from 'react'
import { Link, Outlet } from 'react-router-dom'
export default function Message() {
const [messages] = useState([{
id: '001',
title: '小道消息',
info: '介个就是小道消息~'
}, {
id: '002',
title: '大道消息',
info: '介个就是大道消息!!!'
}, {
id: '003',
title: '大道消息Plus',
info: '介个就是大道消息Plus~'
}])
return (
<div>
<ul>
{
messages.map(m => (
<li key={m.id}>
<Link to={`detail?id=${m.id}&title=${m.title}&nfo=${m.info}`}>{m.title}</Link>
</li>
))
}
</ul>
<Outlet />
</div>
)
}
3、Detail.jsx
- 使用新Hook
useSearchParams
接 search参数
import React from 'react'
import { useSearchParams } from 'react-router-dom'
export default function Detail() {
const [search, setSearch] = useSearchParams()
const id = search.get('id')
const title = search.get('title')
const info = search.get('info')
return (
<>
<ul>
<li>id:{id}</li>
<li>标题:{title}</li>
<li>内容:{info}</li>
</ul>
<button onClick={() => setSearch('id=5000&title=新标题&info=小猪佩奇')}>点我更新search参数</button>
</>
)
}
4、Result
5、另外一个可以获取 search 的新 Hook :useLocation
- 可以用 useLocation,但是正常人不会用它接 search 的值
修改上面 Detail.jsx
import React from 'react'
import { useLocation } from 'react-router-dom'
export default function Detail() {
console.log(useLocation())
// 其他略...
}
- 看一眼控制台