【问题标题】:React-router-v6 access a url parameterreact-router-v6 访问一个url参数
【发布时间】:2022-01-01 16:22:25
【问题描述】:

如何在我的 react 组件中访问 url 参数?

App.js

<Route path="/question/:id" element={<QuestionView />} />

QuestionView.js

class QuestionView extends React.Component {     
    render() {
          const { questions, users } = this.props;
          const {id} = ??? 

【问题讨论】:

    标签: reactjs react-router react-router-dom


    【解决方案1】:

    问题

    在 react-router-dom v6 中,Route 组件不再具有路由属性(historylocationmatch),当前的解决方案是使用这些的 React 钩子“版本”在被渲染的组件中使用。但是 React 钩子不能在类组件中使用。

    要使用类组件访问匹配参数,您必须转换为函数组件,或滚动您自己的自定义 withRouter 高阶组件以注入“路由道具”,例如来自 react-router-dom v5 的 withRouter HOC .x 做到了。

    解决方案

    我不会介绍将类组件转换为函数组件。这是一个示例自定义withRouter HOC:

    const withRouter = WrappedComponent => props => {
      const params = useParams();
      // etc... other react-router-dom v6 hooks
    
      return (
        <WrappedComponent
          {...props}
          params={params}
          // etc...
        />
      );
    };
    

    并用新的 HOC 装饰组件。

    export default withRouter(Post);
    

    这将为类组件注入一个params 属性。

    this.props.params.id
    

    【讨论】:

    • 谢谢,你解决了我的问题
    • 当您从 react-router-dom 导入 withRouter 时出现此错误:尝试导入错误:“react-router-dom”不包含默认导出(导入为“withRouter”)。
    • @SabaoonBedar 这就是这个答案所要解决的问题。 RRDv6 不会导出 withRouter HOC,因此如果您需要一个仍然接收路由道具的“遗留”组件,您必须自己滚动。
    • 感谢您的回复@DrewReese
    • TypeScript 使用 const withRouter = (WrappedComponent: any) =&gt; (props: any) =&gt; { ... };
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-28
    • 2022-07-21
    • 2022-06-18
    • 1970-01-01
    相关资源
    最近更新 更多