// 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>
);
}
引入依赖:
useEffect
和 useState
是 React 的 Hooks,用于管理组件的状态和副作用。axios
是一个常用的 HTTP 客户端库,用于发起 HTTP 请求。状态管理:
useState
创建了一个名为 posts
的状态变量,用于存储从 Strapi 获取的帖子数据。副作用处理:
useEffect
在组件挂载时发起 HTTP 请求,获取 Strapi 中的帖子数据,并将其存储在 posts
状态变量中。渲染数据:
posts
状态变量中映射出来的。API 请求:
http://localhost:1337/api/posts
) 获取帖子数据。请根据实际情况调整 API 地址。错误处理:
如果你需要更复杂的功能或有其他需求,请进一步说明。
上一篇:js instanceof
下一篇:js classname
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站