others - Javascript - React JS:Rendered fewer hooks than expected.这可能是由意外的早期返回语句引起

我尝试对React JS项目进行身份验证,但我得到以下错误:

Rendered fewer hooks than expected. this may be caused by an accidental early return statement.

我用了不同的方法来完成这项工作,但是它们都不适合我。

我在ContextWrapper组件中添加了如下的方法:


import React, { useState, useEffect } from"react";


import { useCookies } from"react-cookie";


import jwt from"jsonwebtoken";


import { fetchLogin, fetchVerify } from"../fake-server";


import Context from"./context";



export default ({ children }) => {


 const [token, setToken] = useState(null);


 const [message, setMessage] = useState(null);


 const [loading, setLoading] = useState(false);


 const [cookies, setCookie, removeCookie] = useCookies(["token"]);



 useEffect(() => {


 console.log(cookies);


 if (cookies.token) {


 setToken(cookies.token);


 }


 }, []);



 useEffect(() => {


 if (token) {


 setCookie("token", JSON.stringify(token), { path:"/" });


 } else {


 removeCookie("token");


 }



 console.log(token);


 }, [token]);



 function login(email, password) {


 fetchLogin(email, password)


 /*.then(response => response.json())*/


 .then(data => {


 const decoded = jwt.decode(data.token);


 const token = {


 token: data.token,


 ...decoded


 };


 setToken(token);


 })


 .catch(error => {


 console.log("error", error);


 setMessage({


 status: 500,


 text: error


 });


 });


 }



 function verify() {


 fetchVerify(cookies.token)


 /*.then(response => response.json())*/


 .then(data => {


 setToken(data);


 })


 .catch(error => {


 setToken(null);


 setMessage({


 status: 500,


 text: error


 });


 });


 }



 function logout() {


 setToken(false);


 }



 const value = {


 login,


 verify,


 logout,


 token,


 message,


 setMessage,


 loading,


 setLoading


 };



 return <Context.Provider value={value}>{children}</Context.Provider>;


};



然后这是Login组件:


import React, { useState, useContext, useEffect } from"react";


import {


 Grid,


 Card,


 Typography,


 CardActions,


 CardContent,


 FormControl,


 TextField,


 Button


} from"@material-ui/core";


import { Redirect } from"react-router-dom";


import { makeStyles } from"@material-ui/core/styles";


import Context from"../context/context";



const useStyles = makeStyles(theme => ({


 root: {


 height:"100vh",


 display:"flex",


 justifyContent:"center",


 alignContent:"center"


 },


 title: {


 marginBottom: theme.spacing(2)


 },


 card: {},


 formControl: {


 marginBottom: theme.spacing(1)


 },


 actions: {


 display:"flex",


 justifyContent:"flex-end"


 }


}));



export default ({ history, location }) => {


 const context = useContext(Context);


 const classes = useStyles();


 const [email, setEmail] = useState("");


 const [password, setPassword] = useState("");



 if (context.token) {


 return <Redirect to="/" />;


 }



 useEffect(() => {


 context.setLoading(false);


 }, []);



 function onSubmit(e) {


 e.preventDefault();


 context.login(email, password);


 }



 return (


 <Grid container className={classes.root}>


 <Card className={classes.card}>


 <form onSubmit={onSubmit}>


 <CardContent>


 <Typography variant="h4" className={classes.title}>


 Login


 </Typography>


 <FormControl className={classes.formControl} fullWidth>


 <TextField


 type="text"


 variant="outlined"


 label="Email"


 value={email}


 onChange={e => setEmail(e.target.value)}


 />


 </FormControl>


 <FormControl className={classes.formControl} fullWidth>


 <TextField


 type="password"


 variant="outlined"


 label="Password"


 value={password}


 onChange={e => setPassword(e.target.value)}


 />


 </FormControl>


 </CardContent>


 <CardActions className={classes.actions}>


 <Button type="submit" variant="contained" color="secondary">


 Login


 </Button>


 </CardActions>


 </form>


 </Card>


 </Grid>


 );


};



这里我创建了沙箱来重现触发login()方法时发生的错误。

时间: 原作者:

useEffect下移动你的条件。


useEffect(() => {})



if (context.token) {


 return <Redirect to="/" />;


}



原作者:

控制台的错误已经告诉了你问题所在,不能创建条件hook,这个hook是一个问题,需要出现在return语句之前,


useEffect(() => {


context.setLoading(false);



},[] );

原作者:
...