react hooks
列表页跳转详情页 带上id 等参数
详情页获取参数判断是否有值 有值的情况下 请求数据
列表页 发起
1.跳转的地方
onClick={() => {
history.push({
pathname: '/list/list-detail',
search: `?id=${id}&type=view`
})
}}>
查看详情
2.history 来源
import { useHistory } from 'react-router-dom'
const TableList: React.FC = () => {
const history = useHistory()
}
详情页 接收
1.接收history里的search字段
在react 中获取
import { useLocation } from 'react-router-dom'
// 列表页传入 详情页接收的字段
export interface ILocationState {
id: string
type: string
}
const DetailForm: React.FC = () => {
const location = useLocation()
const params = new URLSearchParams(location.search)
const id = params.get('id')
}
案例: 浏览器控制台Console 测试
var url = new URL('https://example.com?foo=1&bar=2');
var params = new URLSearchParams(url.search);
params.get('foo') => 1
params.get('bar') => 2
2.判断参数是否有值 有值的情况下handleInfo请求数据 存当前id
const [detailId, setDetailId] = useState('')
useEffect(() => {
if (
params.get('id') !== '' &&
params.get('id') !== undefined &&
params.get('id') !== null
) {
handleInfo(params.get('id'))
setDetailId(params.get('id'))
} else {
setDetailId('')
}
}, [detailId])
标签:const,get,react,详情页,params,跳转,id
来源: https://blog.csdn.net/Embrace924/article/details/115162336