【问题标题】:Getting Error When Trying to Render Page with React Hook尝试使用 React Hook 渲染页面时出错
【发布时间】:2021-07-16 10:33:13
【问题描述】:

在我的 App.js 中,我调用了一个自定义 React Hook。当我尝试使用自定义 React Hook 导航到页面时,它会引发错误:

Error: WithAuth(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null.

我知道这似乎不言自明,但我是 React 新手。如果他们在尝试导航到仪表板页面时未登录,我正在尝试将用户重定向到登录页面。我知道在某个地方我需要返回 null,但我不知道在哪里。任何帮助都是极好的。谢谢。

App.js

import WithAuth from "./hoc/withAuth";
const App = (props) => {
    return (
        <Route
          path="/dashboard"
          render={() => (
            <WithAuth>
              <MainLayout>
                <Dashboard />
              </MainLayout>
            </WithAuth>
          )}
        />
    );
};

withAuth.js

import { useAuth } from "./../customHooks";
import { withRouter } from "react-router-dom";

const WithAuth = (props) => useAuth(props) && props.children;

export default withRouter(WithAuth);

useAuth.js

import { useEffect } from "react";
import { useSelector } from "react-redux";

const mapState = ({ user }) => ({
  currentUser: user.currentUser,
});

const useAuth = (props) => {
  const { currentUser } = useSelector(mapState);

  useEffect(() => {
    if (!currentUser) {
      props.history.push("/login");
    }
  }, [currentUser]);

  return currentUser;
};

export default useAuth;

【问题讨论】:

    标签: javascript reactjs react-router react-hooks


    【解决方案1】:

    我的猜测是您的 useAuth(props) 正在返回一个错误值,因此没有返回任何子级。

    const WithAuth = (props) => useAuth(props) && props.children;
    

    您应该返回 null 以向 React 指示不应渲染任何内容。

    const WithAuth = (props) => useAuth(props) ? props.children : null;
    

    Preventing Component from Rendering

    返回的 JSX 中一般会忽略布尔值除了,当它是返回值时,它必须是有效的 JSX 节点或 null。

    【讨论】:

    • 是的,做到了。我很感激,伙计。也感谢您提供更多信息!
    • @Matt 我没有说出来,但名称前缀"with" 通常是为高阶组件保留的。例如,参见withRouter,它是一个消耗一个组件并返回一个新组件的函数。 WithAuth 这个名字在消耗道具时让我震惊。它更像是一个“包装器”而不是 HOC。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-27
    • 2021-08-16
    • 2020-10-07
    • 2020-05-08
    • 1970-01-01
    相关资源
    最近更新 更多