反应路由器私有路由实现路径道具是否通过?

时间:2021-01-28 14:50:46

标签: javascript reactjs react-router

大家好,这更像是一个请求,询问我对 react.js 中私有路由实现的理解,而不是一个问题。许多带有身份验证的私有路由的实现似乎都发布了相同的代码

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

现在据我所知,这 3 个点是基本分配传递对象的展开运算符。进一步的 SO 答案也证实了它 What do these three dots in React do? 尤其是来自 Mehdi Raash 的答案。现在我的理解是,这基本上意味着 'path' 道具也在 ...rest 对象中传递,就像

<Route path={rest.path} render={(props) => (
        fakeAuth.isAuthenticated === true
          ? <Component {...props} />
          : <Redirect to='/login' />
      )} />

但最近我看到了这篇文章https://ui.dev/react-router-v4-protected-routes-authentication/ 这条线对我来说没有意义

A few notes on the above code. With Route, if a path isn’t supplied, then that Route will always match. So in the case above, because we didn’t supply a path prop, the Route will always match which means the render prop will always be called. 

所以我只想知道这个语句是否正确并且路径道具没有在私有路由实现中传递,如果是,那么这个 {...rest} 在路由中做了什么。

注意:本文作者无意冒犯,如果我错了,我只是想纠正我的理解

1 个答案:

答案 0 :(得分:0)

在您的情况下,spread operator 基本上将所有剩余的属性放入一个名为 rest 的新对象中。假设 PrivateRoute 是这样发起的:

<PrivateRoute component={Home} path="/protected" secure={false} />

component 在您的示例中被解构并重命名为 Component。这意味着 rest 看起来像这样:

rest = {
  path: "/protected",
  secure: false
}

接下来发生的是 rest 对象被传播到 Route。所以这个:

<Route {...rest} render={(props) => ()} />

与此相同:

<Route path={res.path} secure={res.secure} render={(props) => ()} />

或者这个:

<Route path="/protected" secure={false} render={(props) => ()} />

顺便说一下,render() 函数中的 props 只包含 three props,它们来自 Router:

  • 匹配
  • 位置
  • 历史