【问题标题】:How to use reach router with React Context API?如何通过 React Context API 使用到达路由器?
【发布时间】:2020-04-28 13:11:46
【问题描述】:

我之前使用过下面这样的到达路由器,它工作正常

.....
<Router>
   <ComponentA path="/:id">
   <ComponentB path="/">
<Router>
....

我决定用上下文重构我的代码,代码被重构成这样:

<GlobalContextProvider>
  <GlobalContext.Consumer>
  {( context) =>{
  return(
  .....
   <Router>
      <ComponentA path="/:id">
      <ComponentB path="/">
   <Router>
   ....
  }

重构后,ComponentA 无法正常工作,因为 url 参数 prop id 没有传递

在 ComponentA.js 中,像这样测试:

 componentDidMount() {
    const { id } = this.props;
    console.log(id);    // return undefined
  }

当我 console.log(this.props) 时,它返回与 this.context 相同的结果

有人能帮我理解为什么会这样吗?如何正确重构上下文?

非常感谢

【问题讨论】:

    标签: reactjs react-context reach-router


    【解决方案1】:

    我终于弄清楚了这个问题:

    ComponentA 被 HOC 包裹,并通过将 {...this.props} 添加到 ComposedComponent,

    ComponentA可以访问this.props的url参数

    请参考本期Passing React context through an HOC to a wrapped component

    【讨论】:

      【解决方案2】:

      一开始我不确定它是否有效。

      要访问参数值,您必须这样做:

      const { match } = props;
      const { params } = match;
      const { id } = params;
      

      您可能需要将组件包装到 withRouter(...)

      import { withRouter } from "react-router-dom";
      class MyComp extends PureComponent {...}
      export default withRouter(MyComp);
      

      【讨论】:

      • 谢谢你的回答,不过我用reach-router而不是react-router
      • 您是否尝试了其他关键字而不是 id ?因为它可能会被全球消费者覆盖。
      • 我没有在我的项目中使用id,它是别的东西。我以id 为例来描述这个问题。
      猜你喜欢
      • 1970-01-01
      • 2020-07-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-22
      • 2021-03-20
      相关资源
      最近更新 更多