【问题标题】:support render props of react router in route hoc支持在 route hoc 中渲染 react router 的 props
【发布时间】:2019-09-20 23:19:36
【问题描述】:

我正在为公共路线和私人路线编写 HOC。如果路由是私有的并且用户已通过身份验证,则让他/她进入该页面,否则重定向到登录组件。如果路由是公共的并且用户未通过身份验证,则显示页面并显示登录页面,如果用户未通过身份验证但用户已通过身份验证并且仍然进入登录页面,则将用户重定向到根页面。这工作正常。但是如果我使用渲染而不是组件,那么它就不起作用。只有当我从名为 react-router 的组件的 props 中传递组件时,我才能使其工作。

如果用户用户渲染道具,我怎样才能使它工作?

这是我的代码

<Switch>
  <PrivateRoute
    exact
    path="/"
    render={() => <Home name="something" />} {/* this does not work */}
  />
  <PrivateRoute exact path="/demo" component={Demo} />
  <PublicRoute restricted={true} path="/auth" component={Authentication} />
</Switch>

PublicRoute.js

const PublicRoute = ({component: Component, restricted, ...rest}) => {
  return (
    <Route
      {...rest}
      render={props =>
        isLogin() && restricted ? <Redirect to="/" /> : <Component {...props} />
      }
    />
  )
}

PrivateRoute.js

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

另外,如果有任何需要改进的地方,请向我提出建议。

【问题讨论】:

    标签: javascript reactjs react-router-v4


    【解决方案1】:

    问题在于,在您的自定义路由中,您总是使用 component 属性。因此,当传递 render 道具时,它会被您自定义路线中的那个否决,从而尝试呈现提供的 component

    当你像下面的函数一样修改它时,它会起作用。它还提取render 属性,如果它是一个函数,它将使用它而不是component 属性。

    const PrivateRoute = ({component: Component, render, ...rest}) => {
        const renderContent = props => {
            if (!fakeAuth.isAuthenticated) {
                return (
                    <Redirect
                        to={{
                            pathname: "/login",
                            state: { from: props.location }
                        }}
                    />
                )
            }
            return (typeof render === 'function') ? render(props) : <Component {...props} />
        }
    
        return (
            <Route {...rest} render={renderContent} />
        );
    }
    

    【讨论】:

    • 非常感谢这个出色的解决方案。我有一个困惑。如果不能在这里问,我很抱歉,但我的问题是现在用户可以传递组件或渲染道具,所以在检查道具类型时,它可以是所需的组件或根据需要渲染道具,如果我验证两者为required 那么这将是一个问题,因为我只能传递组件道具或渲染道具。
    • 您可以编写自己的验证逻辑,查看stackoverflow.com/a/42284491/829493 了解更多信息。
    • 谢谢,我会看的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-15
    • 2022-11-10
    • 2019-12-05
    • 2021-10-14
    • 2021-03-21
    • 2022-08-22
    相关资源
    最近更新 更多