React-router-v6 访问一个 url 参数 [英] React-router-v6 access a url parameter
问题描述
如何在我的 react 组件中访问 url 参数?
App.js
<Route path="/question/:id" element={<QuestionView />} />
QuestionView.js
QuestionView.js
class QuestionView extends React.Component {
render() {
const { questions, users } = this.props;
const {id} = ???
推荐答案
Issue
在 react-router-dom v6 中,Route
组件不再具有路由属性(history
、location
和 match
),目前的解决方案是使用 React 钩子版本";其中要在正在呈现的组件中使用.但是 React 钩子不能用在类组件中.
Issue
In react-router-dom v6 the Route
components no longer have route props (history
, location
, and match
), and the current solution is to use the React hooks "versions" of these to use within the components being rendered. React hooks can't be used in class components though.
要使用类组件访问匹配参数,您必须转换为函数组件,或者滚动您自己的自定义 withRouter
高阶组件以注入路由道具";就像 react-router-dom
v5.x 中的 withRouter
HOC 一样.
To access the match params with a class component you must either convert to a function component, or roll your own custom withRouter
Higher Order Component to inject the "route props" like the withRouter
HOC from react-router-dom
v5.x did.
我不会介绍将类组件转换为函数组件.这是一个自定义 withRouter
HOC 示例:
I won't cover converting a class component to function component. Here's an example custom withRouter
HOC:
const withRouter = WrappedComponent => props => {
const params = useParams();
// etc... other react-router-dom v6 hooks
return (
<WrappedComponent
{...props}
params={params}
// etc...
/>
);
};
并用新的 HOC 装饰组件.
And decorate the component with the new HOC.
export default withRouter(Post);
这将为类组件注入一个 params
属性.
This will inject a params
prop for the class component.
this.props.params.id
这篇关于React-router-v6 访问一个 url 参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!