【问题标题】:Rewriting custom route to use render prop instead of component prop in React Router在 React Router 中重写自定义路由以使用渲染道具而不是组件道具
【发布时间】:2021-04-19 01:51:27
【问题描述】:

我有一个使用 React Router 的 React 应用程序。我的代码中有一个错误,这是由于我的自定义 ProtectedRoute 组件中的某些问题:

const ProtectedRoute = ({ component, ...args }) => (
  <Route
    component={withAuthenticationRequired(component, {
      onRedirecting: () => <Loading />,
    })}
    {...args}
  />
);

export default ProtectedRoute;

您可以在此处详细阅读我的另一篇文章:Auth0 ProtectedRoute component preventing component from changing with state

但现在我只是想重写此函数以使用 render 道具而不是 component 道具(我认为这是导致问题的原因)。这是我尝试过的,但没有成功:

const ProtectedRoute = ({component: ComponentToRender, path, rest}) => {
    return <Route
        {...rest}
        path={path}
        render={(props) => {
            withAuthenticationRequired(() => (<ComponentToRender {...props}/>), {
                onRedirecting: () => <Loading/>
            })
        }
        }
    />
}

有谁知道如何重写它以使用 render 属性?

谢谢!

【问题讨论】:

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


    【解决方案1】:

    我认为您传递给render 的箭头函数没有返回任何内容,因为您使用的是主体括号而不是returnRead more about arrow functions on MDN

    你可以这样做:

    render={(props) => (
        withAuthenticationRequired(() => (<ComponentToRender {...props}/>), {
            onRedirecting: () => <Loading/>
        })
    )}
    

    【讨论】:

    • 这种方式不会引发任何错误,但不会在页面上呈现我的任何组件,这些组件位于 ProtectedRoute 内
    猜你喜欢
    • 1970-01-01
    • 2020-07-08
    • 2019-03-02
    • 2019-06-08
    • 2019-04-01
    相关资源
    最近更新 更多