【问题标题】:React Component as a propReact 组件作为道具
【发布时间】:2021-12-28 13:37:46
【问题描述】:

我试图将组件作为 props 传递以制作经过身份验证的路由,但在工作时,我试图在文档上搜索如何做到这一点或在网络上搜索,但不幸的是我没有找到。 所以这是我的组件

 import { useSelector } from "react-redux"
 import { Redirect, Route as ReactRoute } from "react-router-dom/cjs/react-router-dom.min"
export const Route = ({isPrivate=false, Component, ...rest}) =>{
    const { acessToken } = useSelector(store=>store)
    return(
        <ReactRoute  {...rest} render={()=> isPrivate === !!acessToken ? <Component/> : <Redirect to={isPrivate ? '/' : '/dashboard'}/>} />
    )
}

谁能给我一个提示?

【问题讨论】:

    标签: reactjs react-redux react-router-dom react-props


    【解决方案1】:

    我理解你想要达到的目标。

    function PrivateRoute ({isPrivate=false, component: Component, ...rest}) {
      const { acessToken } = useSelector(store=>store)
      return (
        <Route
          {...rest}
          render={(props) => isPrivate === !!acessToken 
            ? <Component {...props} />
            : <Redirect to={isPrivate ? '/' : '/dashboard'}/>}
        />
      )
    }
    

    这是一个很好的例子:

    How to implement authenticated routes in React Router 4?

    【讨论】:

      【解决方案2】:

      当你想将组件作为道具传递时,你可以使用下面的方法

      export const Route = (Component) => {
        return (props) => {
          return <Component {...props} {...resourceProps} />;
        };
      };
      
      

      【讨论】:

        猜你喜欢
        • 2018-10-19
        • 1970-01-01
        • 2017-09-06
        • 2021-03-09
        • 2018-08-22
        • 2018-08-01
        • 1970-01-01
        • 2021-02-23
        • 2019-03-20
        相关资源
        最近更新 更多