簡體   English   中英

API 來自 React.FC 的 GET 無法傳遞給組件

[英]API GET from React.FC unable to pass to component

我目前正在嘗試使用 React 前端和 Rails 7.0.1 后端 API 制作一個 webapp。

我正在嘗試從 rails API 獲取數據,但在確定問題是否為以下方面時遇到了麻煩:

  1. 來自 axios 的 GET 過程不正確
  2. 將數據從頁面“Home.tsx”傳遞到組件“ArticlesList.tsx”

這是我的Home.tsx頁面,試圖從 API 獲取數據

const API_URL = 'http://localhost:3000/api/v1/articles';

function getAPIData() {
    return axios.get(API_URL).then((response) => response.data);
}

const Home: React.FC = () => {
    ...

    const [articles, setArticles] = useState([]);
    useEffect(() => {
        getAPIData().then((items) => {
            setArticles(items);
        });
    }, []);

    return (
        <>
            ...
            <br />
            <ArticlesList articles={articles} />
        </>
    );
};

export default Home;

這是我試圖顯示數據的ArticlesList.tsx組件

import Data from '../TestArticles.json';
import React from 'react';
import '../App.css';

interface articles {
    id: number;
    title: string;
    body: string;
}

const ArticlesList: React.FC<{ articles: any }> = ({ articles }) => {
    return (
        <div>
            <h1>{'List of Articles from API'}</h1>
            {articles.map((article: any) => (
                <div key={article.id}>
                    <h2>{article.title}</h2>
                    <p>{article.body}</p>
                </div>
            ))}
        </div>
    );
};

export default ArticlesList;

我相信問題不在於組件,因為通過使用 .json 文件進行測試,我可以在頁面上加載我的條目。 見照片:當前頁面與預期頁面

我很新,也很感謝任何關於改進或排除代碼故障的建議!

我從控制台收到訪問控制允許來源錯誤。 Richard Peck 的解決方案解決了這個問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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