簡體   English   中英

無法使用 Hook Inside React Function

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM