【问题标题】:React Router pass route parameter from parent to childReact Router 将路由参数从父级传递给子级
【发布时间】:2021-01-17 12:30:37
【问题描述】:

您好,我已经为 react 中的 Route 组件创建了一个包装器,称为 PrivateRoute。

我希望能够从这个内部调用一个 Page 组件并将路径的 :id 传递给它,所以我是这样称呼它的:

 <PrivateRoute exact path="/page/:id"
   render={() => <Page secure={true} resource="/pages/" />}/>

但是在我想要访问路由参数的页面组件内部。

  componentDidMount() {
    this.getEntity(this.props.match.params.id);
  }

this.props.match.params.id 显示为未定义。

以前我有这个:

<PrivateRoute path="/pages/:id" component={Page} />

Page 收到了 id。通过 this.props.match.params.id 但后来我不知道如何将其他道具传递给页面,这就是我更改它的原因。

这是我的路由包装器的实现

class PrivateRoute extends React.Component {
  render() {
    const { isLoggedIn, children, ...rest } = this.props;
    const loggedIn = localStorage.getItem('loggedIn');
    if (loggedIn == "true") {
      return <Route {...rest}>{children}</Route>;
    } else {
      return (
        <Redirect
          to={{
            pathname: "/login",
            state: { referrer: this.props.location }
          }}
        />
      );
    }
  }
}

有人知道我应该怎么做吗?

谢谢

【问题讨论】:

    标签: reactjs react-router


    【解决方案1】:

    问问自己:“‘这’是什么?”。在以下情况下:

    componentDidMount() {
      this.getEntity(this.props.match.params.id);
    }
    

    this.props 不属于来自PrivateRoute 组件的属性。

    解决方案:

    将 prop id 添加到 Page 组件并像这样传递 id:

    <PrivateRoute exact path="/page/:id"
       render={({ match }) => <Page secure={true} resource="/pages/" id={match.params.id} />}/>
    

    【讨论】:

    • 有一件事我还是不明白,你怎么知道你可以将匹配传递给渲染?你能解释一下吗?或者你知道一个链接吗?
    • @Amir React Router 文档有一个关于“匹配”对象的部分以及可以访问它的位置:v5.reactrouter.com/web/api/match
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-09
    • 1970-01-01
    • 2020-01-12
    • 2020-09-09
    • 2016-05-13
    • 1970-01-01
    相关资源
    最近更新 更多