我开始学习React Js了。我试图用钩子创建一个auth。但我收到了一个错误:
Unhandled Rejection (Error): Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside
componentWillUpdate或componentDidUpdate。React限制嵌套更新以防止无限循环。
这是我的代码,我试图简化组件,我希望它是清晰的
export const AuthContext = React.createContext();
export const AuthProvider = ({children}) => {
const [currentUser, setCurrentUser] = useState(null);
useEffect( () => {
//const token = localStorage.getItem( 'token' );
//const userName = localStorage.getItem( 'userName' );
console.log('useEffect Auth Provider');
console.log(currentUser);
}, [] );
return (
<AuthContext.Provider
value={
[currentUser, setCurrentUser]
}
>
{children}
</AuthContext.Provider>
);
}
当我尝试登录login.js:时
export const Login = () => {
const [ currentUser, setCurrentUser ] = useContext( AuthContext );
// Login
const handleLogin = (event) => {
event.preventDefault();
const { email, password } = event.target.elements;
console.log(email.value, password.value);
const siteUrl = clientConfig.serverUrl;
const loginData = {
email: email.value,
password: password.value
};
axios.post( `${siteUrl}/api/users/login`, loginData )
.then( res => {
setCurrentUser(res.data);
console.log(res.data);
});
}
if (currentUser) {
return <Redirect to="/" />
}
else {
return (
<form onSubmit={handleLogin}>
<input name="email" type="text" placeholder="E-Mail"></input>
<input name="password" type="password" placeholder="**************"></input>
<button type="submit">Login</button>
</form>
);
}
};
App.js:
function App() {
return (
<AuthProvider>
<Router>
<Switch>
<PrivateRoute exact path="/" component={Home} />
<Route exact path="/login" component={Login} />
<Route path="*" component={NotFound} />
</Switch>
</Router>
</AuthProvider>
);
}
export default App;
//私有路由
import React, { useContext } from "react";
import { Route, Redirect } from "react-router-dom";
import { AuthContext } from "../context/auth";
export const PrivateRoute = ({ component: RouteComponent, ...rest }) => {
const {currentUser} = useContext(AuthContext);
return (
<Route
{...rest}
render={routeProps =>
!!currentUser ? (
<RouteComponent {...routeProps} />
) : (
<Redirect to={"/login"} />
)
}
/>
);
};
我哪里错了?感谢任何想帮助我的人。马可意大利
以下是您的代码的工作版本:
https://codesandbox.io/s/focused-dubinsky-yhpcl
问题出在您在PrivateRoute上访问当前用户的方式上。它以undefined
的形式返回。
const { currentUser } = useContext(AuthContext);
你不能那样破坏数组。所以我改成了这个:
const [currentUser, setCurrentUser] = useContext(AuthContext);
注意:我知道你不需要PrivateRoute
上的setCurrentUser
。但这只是一种让它正常工作的方法。你也可以这样做:
const [currentUser] = useContext(AuthContext);
//当您获得第一个数组值时,这是有效的
PrivateRoute.js
export const PrivateRoute = ({ component: RouteComponent, ...rest }) => {
console.log("Rendering PrivateRoute...");
const [currentUser, setCurrentUser] = useContext(AuthContext); // <-------------
console.log("currentUser: " + currentUser);
return (
<Route
{...rest}
render={routeProps =>
!!currentUser ? (
<RouteComponent {...routeProps} />
) : (
<Redirect to={"/login"} />
)
}
/>
);
};