Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

next.js strapi

作者:炼狱死神   发布日期:2025-03-29   浏览:121

// pages/index.js
import { useEffect, useState } from 'react';
import axios from 'axios';

export default function Home() {
  const [posts, setPosts] = useState([]);

  useEffect(() => {
    // Fetch data from Strapi API
    axios.get('http://localhost:1337/api/posts')
      .then(response => {
        setPosts(response.data);
      })
      .catch(error => {
        console.error('Error fetching posts:', error);
      });
  }, []);

  return (
    <div>
      <h1>Next.js with Strapi</h1>
      <ul>
        {posts.map(post => (
          <li key={post.id}>{post.title}</li>
        ))}
      </ul>
    </div>
  );
}

解释说明

  1. 引入依赖

    • useEffectuseState 是 React 的 Hooks,用于管理组件的状态和副作用。
    • axios 是一个常用的 HTTP 客户端库,用于发起 HTTP 请求。
  2. 状态管理

    • 使用 useState 创建了一个名为 posts 的状态变量,用于存储从 Strapi 获取的帖子数据。
  3. 副作用处理

    • 使用 useEffect 在组件挂载时发起 HTTP 请求,获取 Strapi 中的帖子数据,并将其存储在 posts 状态变量中。
  4. 渲染数据

    • 组件返回一个包含标题和列表的 JSX 结构。列表中的每一项都是从 posts 状态变量中映射出来的。
  5. API 请求

    • 发起 GET 请求到 Strapi API (http://localhost:1337/api/posts) 获取帖子数据。请根据实际情况调整 API 地址。
  6. 错误处理

    • 如果请求失败,会在控制台输出错误信息。

如果你需要更复杂的功能或有其他需求,请进一步说明。

上一篇:js instanceof

下一篇:js classname

大家都在看

js 数组对象排序

js 数组删掉第一个值

js fill

js 数组复制

js 复制数组

js 数组拷贝

js 对象转数组

js 深拷贝数组

js 获取今天年月日

js jsonp

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站