【发布时间】: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