【问题标题】:Fetch data request to nested JSON object error - React/Next.JS获取嵌套 JSON 对象的数据请求错误 - React/Next.JS
【发布时间】:2019-09-16 00:46:04
【问题描述】:

我在从我的 API 获取数据时遇到问题,我收到了这个错误。我在下面附上了 JSON 格式,因为我认为这是我的结构的问题。当我对嵌套在数组中的对象使用不同的 res URL 时,它可以工作。但就我的数据而言,事实并非如此。谁能帮帮我?

"Index.getInitialProps()" 应该解析为一个对象。而是发现未定义”

import Layout from '../comps/Layout';
import Link from 'next/link';
import fetch from 'isomorphic-unfetch';

const Index = props => (
<Layout>
    //List of movies here
</Layout>
);

Index.getInitialProps = async function() {
    const res = await fetch('https://www.what-song.com/api/recent-movies')
    const data = await res.json()

    console.log(`Data: ${data}`)

}

export default Index;

【问题讨论】:

  • 那个代码结构有点奇怪......你能发布使用你的索引组件的代码吗?另外,我不认为你可以在反应中附加这样的功能,除非你正在使用一个类。 (我说的是你创建getInitialProps 的方式)

标签: javascript json reactjs next.js


【解决方案1】:

getInitialProps 方法基本上应该将您的组件设置为初始props。但是,在您的情况下,您什么也没有返回。

所以,把你的代码改成

Index.getInitialProps = async function() {
    const res = await fetch('https://www.what-song.com/api/recent-movies')
    const data = await res.json()

    console.log(`Data: ${data}`)
    return { data }; // <-- set whatever key you want.
}

为了你的reference

【讨论】:

    猜你喜欢
    • 2018-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-17
    • 1970-01-01
    • 1970-01-01
    • 2019-12-01
    相关资源
    最近更新 更多