【发布时间】:2022-02-02 19:19:33
【问题描述】:
我正在做一个项目的前端,我被困了一段时间。 我用 django rest 框架创建了一个 api,我正在尝试连接到 Nextjs 前端。数据将显示在首页上,这就是我调用 getInitialProps 的原因。以下是代码
import styles from '../styles/Home.module.css';
import axios from 'axios';
const Home = ({ listings, error }) => {
if (error) {
return <div>An error occured: {error.message}</div>;
}
return (
<ul>
{listings.map((listing) => (
<li key={listing.address}>{listing.title}</li>
))}
</ul>
);
};
Home.getInitialProps = async (ctx) => {
try {
const res = await axios.get('http://127.0.0.1:8000/api/listings/?page=4');
const rep = await res.data;
console.log(rep.results);
listings = rep.results;
return { listings };
} catch (error) {
return { error };
}
};
export default Home;
在控制台日志中,我得到数据,格式如下:
[
{
index: 1734112,
user: 11233,
title: 'Classical style',
address: 'address 23, city , country',
bedrooms: '2',
bethrooms: '1',
price: '5803',
list_type: 'rent'
},
{
index: 1722303,
user: 32119,
title: 'Pangrati On the Lake',
address: 'address 28, city , country',
bedrooms: '1',
bethrooms: '1',
price: '4800',
list_type: 'rent'
}
]
但是我在没有指定错误的情况下在浏览器中发生错误。
在控制台中,我得到以下信息。
next-dev.js?3515:32 Warning: Did not expect server HTML to contain the text node "listings is not defined" in <div>.
at div
at Home (webpack-internal:///./pages/index.js:50:26)
at MyApp (webpack-internal:///./pages/_app.js:38:27)
at ErrorBoundary (webpack-internal:///./node_modules/next/dist/compiled/@next/react-dev-overlay/client.js:8:20584)
at ReactDevOverlay (webpack-internal:///./node_modules/next/dist/compiled/@next/react-dev-overlay/client.js:8:23125)
at Container (webpack-internal:///./node_modules/next/dist/client/index.js:359:9)
at AppContainer (webpack-internal:///./node_modules/next/dist/client/index.js:793:26)
at Root (webpack-internal:///./node_modules/next/dist/client/index.js:915:27)
我不确定问题出在哪里,因此非常感谢您的帮助。谢谢!
【问题讨论】:
-
你看过this吗?