我正在尝试让我的privateRoute等待我的API调用。确定用户是否在线并允许访问该页面。但我收到以下错误:
错误:
Error: PrivateRoute(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null.
我认为自从我在等待我的服务器以来,它就没有在等待响应了。我该如何解决才能等待?
我这样称呼它:
服务器响应专用路由:
import React from 'react';
import PropTypes from 'prop-types';
import { Route, Navigate } from 'react-router-dom';
import { useNavigate } from "react-router-dom";
import Login from './components/login/login.jsx';
import GameComponent from './gameComponent.jsx';
import axios from 'axios';
const PrivateRoute = ({ component: Component, redirectTo, isAuth, path, ...props }) => {
//isAuth = false;
axios.post(`http://localhost:3000/online`,{withCredentials: true})
.then(res => {
console.log(res);
if (res) {
isAuth = true;
} else {
isAuth = false;
}
if(!isAuth) {
return <Navigate to={redirectTo} />;
}
return <Route path={path} element={<Component />} />
});
};
export default PrivateRoute;
旧代码:
const PrivateRoute = ({ component: Component, redirectTo, isAuth, path, ...props }) => {
//isAuth = false;
// no code checking... or real auth
if(!isAuth) {
return <Navigate to={redirectTo} />;
}
return <Route path={path} element={<Component />} />
};
export default PrivateRoute;
更新:请记住,它必须与React-route版本6一起使用
答案 0 :(得分:1)
您会在这里找到我的摄入物:https://codesandbox.io/s/react-router-basic-forked-m0624?file=/private.js(请参阅private.js文件,我为topic
路线(主题按钮)创建了一条私人路线)
您的第一个错误是您的PrivateRoute组件未返回任何内容。您将必须执行return axios.post
至少返回某些内容(该内容会导致错误)。
然后为axios.post
是一个异步函数,需要花费一些时间才能解决,在提取时PrivateRoute不会呈现任何内容,因此您必须确保PrivateRoute至少在返回时返回loading
组件它获取。
if (isLoading) return <div>loading</div>;
然后在您的以下代码中,如果您这样更改变量,React将不执行任何操作。 (这样它就不会对更改做出“反应”)
isAuth = true;
} else {
isAuth = false;
}
您必须创建一个让[isAuth, setIsAuth] = React.useState(false)
这样的钩子函数,并像setIsAuth(true)
这样来更改变量。在我的解决方案中,我为isAuth
和isLoading
制作了一个自定义钩子,以获取和设置变量,以便React可以对它们的更改做出反应并呈现出良好的组件。