我是 nextjs 的新手,正在向你们这些了不起的人寻求帮助
我想知道如何在服务器端的 nextjs 中单击按钮时从 api 获取数据。
我知道如果不将其设为客户端,我们就无法使用 onclick,但我不想将其设为客户端
这是我的代码,我直接从服务器获取数据
import Button from "@/components/button/Button";
import { get } from "@/services/ApiService";
import React from "react";
const getData = async() => {
console.log("data from server")
const response = await get(`posts`)
return response?.data
}
async function About() {
const data = await getData();
return (
<div>
Welcome to About test
<Button data="posts" />
{data &&
data.map((item, index) => {
return (
<div key={index}>
<div>{item.id}</div>
<div>{item.title}</div>
</div>
);
})}
</div>
);
}
export default About;
我认为你想做的事情与此类似?
您需要一个按钮处理程序来在单击时触发该功能,以便您可以设置内部组件状态来渲染数据。
import Button from "@/components/button/Button";
import { get } from "@/services/ApiService";
import React, {useState} from "react";
const getData = async() => {
console.log("data from server")
const response = await get(`posts`)
return response?.data
}
const About = () => {
const [data, setData] = useState(null)
const handleClick = async() => {
const data = await getData()
setData(data)
}
return (
<div>
Welcome to About test
<Button onClick={handleClick} />
{data &&
data.map((item, index) => {
return (
<div key={index}>
<div>{item.id}</div>
<div>{item.title}</div>
</div>
);
})}
</div>
);
}
export default About;
但是评论中提到的方法是这样的,您可以在页面从服务器加载之前获取数据,然后在不单击按钮的情况下渲染它。但是您可以选择将其存储在另一个状态值中,然后在单击时加载已检索到的数据,有点像 isVisible 状态。
import Button from "@/components/button/Button";
import { get } from "@/services/ApiService";
import React from "react";
const getData = async () => {
console.log("data from server");
const response = await get(`posts`);
return response?.data;
};
export async function getServerSideProps() {
const data = await getData();
return {
props: {
data,
},
};
}
const About = ({ data }) => {
return (
<div>
Welcome to About test
<Button />
{data &&
data.map((item, index) => {
return (
<div key={index}>
<div>{item.id}</div>
<div>{item.title}</div>
</div>
);
})}
</div>
);
};
export default About;