[英]Cannot use Hook Inside React Function
使用useEffect
挂钩时,我遇到了invalid hook call error
。 文档仅指定由于版本不匹配或我的 function 调用不正确而发生此问题。
谁能检查一下我犯了哪一部分的错误?
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>
</>
);
}
请假设所有依赖项都已安装,并且username
是预定义的字符串。
真挚地,
cpy24
useEffect(() => {
fetch("/accounts/api/" + username)
.then(res => res.json())
.then((result) => {
setIsLoaded(true);
setItems(result.items);
})
.catch((error) => {
setIsLoaded(true);
setError(error);
});
}, []);
使用catch
处理错误。
尝试按照评论中的建议使用 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])
react 和 react-dom 的版本是什么? (我无法评论)
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();
}, []);
我真的很感谢那些试图回答我的问题的人。 事实证明,我将此组件加载到另一个组件中,这违反了规则。 向所有在此过程中试图提供帮助的人投了赞成票。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.