1.检查Next.js组件的生命周期方法是否正确使用。例如,如果你将API函数作为server-side-only方法定义,则仅在服务器端执行。
class MyComponent extends React.Component { static async getInitialProps({ req }) { const res = await fetch('https://api.example.com/data'); const data = await res.json();
return {
data
};
}
render() { return (
2.如果你在客户端要调用API函数,使用循环调用fetch()或axios()等库。这种方法在Next.js中特别适用,因为它支持客户端和服务器端的渲染。
import axios from 'axios';
class MyComponent extends React.Component { state = { data: [] };
async fetchMyAPI() { const res = await axios.get('/api/data'); const data = await res.json();
this.setState({ data });
}
componentDidMount() { this.fetchMyAPI(); }
render() { return (
3.使用Next.js的API路由来编写服务器端的API函数。这样可以确保API函数在服务器和客户端都能正常执行。
// pages/api/data.js export default function handler(req, res) { res.json({ data: 'Hello World' }); }
// MyComponent.js class MyComponent extends React.Component { state = { data: [] };
async componentDidMount() { const res = await fetch('/api/data'); const data = await res.json();
this.setState({ data });
}
render() { return (
上一篇:API函数无法运行