【问题标题】:React-Router render : Functions are not valid as a React childReact-Router 渲染:函数作为 React 子级无效
【发布时间】:2021-11-09 01:04:21
【问题描述】:
  1. 我创建了一个 HOC“ProtectedRoute”来限制未经身份验证的用户的路径。我在应用程序中使用“react-router-dom”进行路由。

  2. 我可以根据用户的令牌路由用户,但我在控制台中收到警告,并且我无法访问渲染组件中的 routerprops,例如“history”、“location”、“match”。下面是 ProtectedRoute 组件实现。

    const ProtectedRoute = ({component:Component, ...rest}) => {
        const [isLoggedIn, setLoggedIn] = useState({loggedIn:false, loaded:false})
        useEffect(async () => {
            const userStatus = await validateUserLoggedIn();  # returns true if user is authenticated
            setLoggedIn((prevState) => {return {loggedIn:userStatus, loaded:true}})
        }, [])
    
        return(
            <Route {...rest} render={(routerProps) => {
                return isLoggedIn.loaded ?
                isLoggedIn.loggedIn ? <Component {...routerProps} {...rest} /> : <Redirect to={{pathname:'/login'}} :
                <h1>Loading Page</h1>
            }} />
        )
    }
    
  3. 主路由组件中的ProtectedRoute:

    <Switch>
        <ProtectedRoute exact path="/admin" component={Admin} />
    </Switch>
    
  4. 错误消息“函数作为 React 子级无效。如果您返回组件而不是从渲染中返回,则可能会发生这种情况。或者您可能打算调用此函数而不是返回它”。

欢迎提出任何建议。

【问题讨论】:

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


    【解决方案1】:

    好的,所以有一些问题。

    1. 您不应该在组件内返回某些内容,您是在 &lt;Route /&gt; 组件内执行此操作。这导致了警告:Functions are not valid as a React child. This may happen if you return a Component instead of from render。

    2. 您的&lt;Redirect /&gt; 组件在其末尾缺少/&gt;,将其打开会导致错误。

    这些修复也应该可以解决您无法访问路线道具的问题。

        <Route
        {...rest}
        render={(routerProps) => {
          isLoggedIn.loaded ? (
            isLoggedIn.loggedIn ? (
              <Component {...routerProps} {...rest} />
            ) : (
              <Redirect to={{ pathname: '/login' }} />
            )
          ) : (
            <h1>Loading Page</h1>
          );
        }}
      />;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-15
      • 2018-10-18
      • 1970-01-01
      • 2018-11-05
      • 1970-01-01
      相关资源
      最近更新 更多