useParams和props.match.params的对比
注意: withRouter在 react-router 6的版本被废弃了 !!!!
1. useParams 的原理是 React Hooks,可以直接在函数式组件中使用,比较方便
2. props.match.params 则需要使用 withRouter 高阶函数(HOC)包装一下组件,否则无法调用props.match.params
useParams 例子:
import {useParams} from 'react-router-dom'
export const Test = () => { const params = useParams() return <div>xxx</div> }
props.match.params 例子:
import {withRouter} from 'react-router-dom' // v6下的版本
const TextComponent = (props) => { const params = props.match.params // 如果没有使用withrouter,这里会为空或报错 return <div>xxx</div> } export const Text= withRouter(TextComponent)
温馨建议: 使用hooks写出的代码逻辑性会更强、可读性也会更高,所以请尽量使用hooks 😙
那时候我只有一台录音机也没有电脑 也不敢奢求说唱会让自己的生活变好