[英]Cannot use Hook Inside React Function
I faced an invalid hook call error
when using the useEffect
hook.使用
useEffect
挂钩时,我遇到了invalid hook call error
。 The docs only specified that this problem occurred because of either a version mismatch or my function call is incorrect.文档仅指定由于版本不匹配或我的 function 调用不正确而发生此问题。
Can anyone please check which part did I made my mistake?谁能检查一下我犯了哪一部分的错误?
import React, { useState, useEffect } from "react";
import "antd/dist/antd.css";
import { Typography, Card, Avatar, Row, Col, Tooltip } from "antd";
import {
UserOutlined,
BookOutlined,
LogoutOutlined,
SettingOutlined
} from "@ant-design/icons";
const { Text } = Typography;
export default function ProfileCard() {
const [error, setError] = useState(null);
const [isLoaded, setIsLoaded] = useState(false);
const [items, setItems] = useState([]);
useEffect(() => {
fetch("/accounts/api/" + username)
.then(res => res.json())
.then(
(result) => {
setIsLoaded(true);
setItems(result.items);
},
(error) => {
setIsLoaded(true);
setError(error);
}
)
}, [])
return (
<>
<Card
size="small"
style={{ width: 300 }}
actions={[...]}
>
<Row justify="center" style={{ marginBottom: -3 }}>
<Col>
<Text strong style={{ fontSize: 17 }}>
{ items.username }
</Text>
</Col>
</Row>
</Card>
</>
);
}
Please assume that all dependencies are installed and username
is a predefined string.请假设所有依赖项都已安装,并且
username
是预定义的字符串。
Sincerely,真挚地,
cpy24 cpy24
useEffect(() => {
fetch("/accounts/api/" + username)
.then(res => res.json())
.then((result) => {
setIsLoaded(true);
setItems(result.items);
})
.catch((error) => {
setIsLoaded(true);
setError(error);
});
}, []);
use catch
for Error.使用
catch
处理错误。
Try wrapping the fetch with a useCallback hook as suggested in the comments尝试按照评论中的建议使用 useCallback 挂钩包装 fetch
const fetchData = useCallback(() => {
fetch("/accounts/api/" + username)
.then(res => res.json())
.then(
(result) => {
setIsLoaded(true);
setItems(result.items);
},
(error) => {
setIsLoaded(true);
setError(error);
}
)
}, [])
useEffect(() => {
fetchData()
}, [fetchData])
what are the versions of react and react-dom? react 和 react-dom 的版本是什么? (I cannot comment)
(我无法评论)
IIRC you have to declare the function inside the useEffect IIRC,您必须在 useEffect 中声明 function
useEffect(() => {
const fetchData = async () => {
try {
let response = await fetch(`/accounts/api/${username}`);
let result = await response.json();
setIsLoaded(true);
setItems(result.items);
} catch(err) {
console.error(err);
setIsLoaded(true);
setItems(err);
}
};
fetchData();
}, []);
I really appreciated those who tried to answer my question.我真的很感谢那些试图回答我的问题的人。 It turned out that I loaded this component inside another and that's a violation of rules.
事实证明,我将此组件加载到另一个组件中,这违反了规则。 Upvoted to all those that tried to help out along the way.
向所有在此过程中试图提供帮助的人投了赞成票。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.