嗨,我在 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 }
}}
/>
);
}
}
}
有人知道我应该怎么做吗?
谢谢
答案 0 :(得分: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} />}/>