gpt4 book ai didi

javascript - React JS : Rendered fewer hooks than expected. 这可能是意外提前返回语句导致的

转载 作者:行者123 更新时间:2023-12-05 01:38:25 26 4
gpt4 key购买 nike

我正在尝试为 React JS 项目进行身份验证,但出现以下错误:

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

我正在阅读其他问题(如 thisthis),但我想我的情况有所不同,因为我在创建组件后设置了所有 useState

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

我在 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>
);
};

这里我创建了this sandbox重现触发 login() 方法时发生的错误。那么,我做错了什么?

最佳答案

将您的条件移动到 useEffect 下。

useEffect(() => {})

if (context.token) {
return <Redirect to="/" />;
}

因为您的 if 条件影响了它下面的后续 Hook ,因为如果 context.token 为真,它就不会运行。这违反了 Rules of Hooks .

专业提示:按照 React-Docs 中的建议添加 ESlint 插件,以便在您编码时获得这些警告/错误。

关于javascript - React JS : Rendered fewer hooks than expected. 这可能是意外提前返回语句导致的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59899419/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com