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  😙

react-router官方文档传送门

posted @ 2022-06-15 21:47  大熊丨rapper  阅读(772)  评论(0编辑  收藏  举报