Strapi 博客 + React 前端。获取 API 说明

问题描述 投票:0回答:0

我正在尝试使用 Strapi 作为 cms 并使用 React 作为前端来创建一个博客。我一直在玩弄并试图将所有东西连接起来,但我很难理解为什么当我将 json 保存在状态中而不使用

setPosts(json);
进行钻取时,当我使用
return <div className="test">{posts.data[0].attributes.Title}</div>;
渲染时似乎无法访问它。

但是,如果我使用

setPosts(json.data[0].attributes);
保存状态中的属性。我可以使用
return <div className="test">{posts.Title}</div>;
访问标题非常好。

完整代码:

import React, { useState, useEffect } from "react";

// functional react app
const App = () => {
    const [posts, setPosts] = useState({});

    useEffect(() => {
        const url = "http://localhost:1337/api/blogs";
        const options = {
            headers: {
                Authorization: process.env.REACT_APP_STRAPI_TOKEN,
            },
        };
        const fetchData = async () => {
            try {
                const res = await fetch(url, options);
                const json = await res.json();
                // this works but would ideally like to use setPosts(json).
                setPosts(json.data[0].attributes);
                console.log(json);
            } catch (err) {
                console.log(err);
            }
        };

        fetchData();
    }, []);
    return <div className="test">{posts.Title}</div>;
};

export default App;

当我尝试使用邮递员请求“http://localhost:1337/api/blogs”时的完整响应是

{
    "data": [
        {
            "id": 1,
            "attributes": {
                "Title": "First Blog Post",
                "CreationDate": "2023-03-29",
                "Content": "My first blog test. Grabbing API endpoints.\n\nimage in the middle of the  text.\n```\ntest code\n```\n\n\n![Screenshot 2023-02-26 at 6.23.08 PM.png](http://localhost:1337/uploads/Screenshot_2023_02_26_at_6_23_08_PM_ca2f96ffd1.png)",
                "createdAt": "2023-03-30T02:01:59.255Z",
                "updatedAt": "2023-03-30T02:02:06.214Z",
                "publishedAt": "2023-03-30T02:02:06.123Z"
            }
        },
        {
            "id": 2,
            "attributes": {
                "Title": "Blog 2 ",
                "CreationDate": "2023-04-01",
                "Content": "test content 2",
                "createdAt": "2023-04-02T20:53:26.950Z",
                "updatedAt": "2023-04-02T20:53:30.963Z",
                "publishedAt": "2023-04-02T20:53:30.884Z"
            }
        }
    ],
    "meta": {
        "pagination": {
            "page": 1,
            "pageSize": 25,
            "pageCount": 1,
            "total": 2
        }
    }
}

我已经尝试了几种保存状态和访问状态的变体,但似乎无法弄清楚为什么我不能按原样保存 json 并访问它。

reactjs fetch-api strapi
© www.soinside.com 2019 - 2024. All rights reserved.