【问题标题】:Next js with django api rendering dataNext js 用 django api 渲染数据
【发布时间】: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吗?

标签: django axios next.js


【解决方案1】:

您正在为某个变量 listings = rep.results; 赋值,但该变量未声明,您不能在严格模式下执行此操作(我认为在这种情况下这是默认设置)

所以只需将其声明为 const,错误就会消失:

const listings = rep.results

【讨论】:

  • 非常感谢您抽出宝贵时间,菜鸟错误。现在可以使用了。
猜你喜欢
  • 1970-01-01
  • 2021-02-26
  • 2020-04-08
  • 2021-03-30
  • 2021-11-20
  • 1970-01-01
  • 1970-01-01
  • 2021-09-08
  • 2019-11-05
相关资源
最近更新 更多