【问题标题】:React Private Routing through id通过 id 反应私有路由
【发布时间】:2021-01-21 17:50:34
【问题描述】:

所以我在 React 中使用 PrivateRoute 来提供一些组件。在我指定如下的确切路径之前,一切都运行良好:

<PrivateRoute exact path="/info/:id" render={(props) => <BookInfo {...props} />} />

如果我使用Route 正常提供上述路径,则上述路径可以正常工作,但通过PrivateRoute 进行路由会给我以下错误。

PrivateRoute.js

import React from 'react'
import { Route, Redirect } from 'react-router-dom';
import { connect } from 'react-redux';

const PrivateRoute = ({ component: Component, auth, ...rest}) => (
    <Route {...rest} render={ props => 
        auth.isAuthenticated === true ?
        (<Component {...props}/>) : (<Redirect to ='/login'/>)}/>
)

const mapStateToProps = state => ({
    auth: state.auth
})

export default connect (mapStateToProps)(PrivateRoute);

我不知道是什么原因造成的,非常感谢一些帮助。

【问题讨论】:

  • PrivateRoute 需要一个 component 属性才能被传递。您在调用 &lt;PrivateRoute exact path="/info/:id" render={(props) =&gt; &lt;BookInfo {...props} /&gt;} /&gt; 时缺少该道具
  • 我该如何解决这个问题?
  • 试试这个&lt;PrivateRoute exact path="/info/:id" component={BookInfo} /&gt;

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


【解决方案1】:

问题

您的 PrivateRoute 组件期望传递 component 道具,它不处理 Route 组件句柄的其他道具。

const PrivateRoute = ({
  component: Component, // <-- only handles component prop
  auth, ...rest
}) => (
  <Route {...rest} render={ props => 
    auth.isAuthenticated === true ?
    (<Component {...props}/>) : (<Redirect to ='/login'/>)}/>
)

解决方案

component 属性上传递您的 BookInfo,以便通过管道传递。

<PrivateRoute exact path="/info/:id" component={BookInfo} />

重构您的 PrivateRoute 组件以呈现 Route 以及传递给它的所有道具,或 Redirect 组件。

const PrivateRoute = ({ auth, ...props }) => auth.isAuthenticated ? (
    <Route {...props} />
  ) : (
    <Redirect to ='/login'/>
  );

【讨论】:

    猜你喜欢
    • 2018-11-05
    • 2022-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-24
    • 2020-10-22
    • 2020-03-04
    • 2021-01-03
    相关资源
    最近更新 更多