【问题标题】:getInitialProps import data in Next.jsgetInitialProps 在 Next.js 中导入数据
【发布时间】:2019-04-26 21:41:33
【问题描述】:

我在NEXT.js 中有一个简单的页面,例如:

function Page({ stars }) {
    return <div>Next stars: {stars}</div>;
}

Page.getInitialProps = async ({ req }) => {
    const res = await fetch('https://api.github.com/repos/zeit/next.js');
    //console.log(res) shows data at-it-is, -raw
    const json = await res.json();
    return { stars: json.stargazers_count };
};

export default Page;

以及来自 API https://directmarketaccess.ru/api/curves/curves/3 的数据集 采用 Google React Chart 所需的格式,它们的视图完全相同,如下所示:

[
   [header1,..headerX]
   ...
   [valueY,...valueY]
]

这不是object{},而是arrays 中的array

根据来自 Google Charts Demo line chart 的数据集 - 数组数组很好

我花了将近两天的时间来了解这个案例和这样的教程:

并从 google/SO/etc 中搜索答案。可能我不明白某些事情或遗漏了一件琐碎的事情,但在某些情况下,即使在console.log(res) 阶段之后,使用getInititalProps 导入数据后,每次尝试导入不是对象的所有内容时都会收到错误消息与属性。有趣的是,在所有实验之后console.log(res) 正确显示数据,即使服务器拒绝为我呈现页面。那么如果必要的数据是stringnumberarray,而不是object(让我们跳过 typeof array === object 的部分)。如何在有或没有getInitialProps的情况下导入必要格式的数据?

有什么方法可以按原样导入页面上的数据(例如从其他文件中的异步函数,连接到数据库(mongo)并从中接收数据),或者我总是应该使用 API 中的fetch哪个应该发给我object{prop: value} 模型?

【问题讨论】:

    标签: javascript reactjs next.js


    【解决方案1】:

    您可以将任何类型的数据作为对象的属性,包括数组数组。

    只需获取数据,并在getInitialProps 中,将其返回为:

    function Page({ data }) {
        // render your chart here with `data`
    }
    
    Page.getInitialProps = async ({ req }) => {
        const res = await fetch(GOOGLE_CHARTS_API);
        const json = await res.json(); // `json` is your array of arrays of data
        return { data: json };
    };
    
    export default Page;
    

    【讨论】:

    • 我稍后会再次重新测试这个解决方案,但上次它触发了像React child component...这样的打印错误
    • @AlexZeDim 随时使用您正在使用的完整代码添加更多信息。
    • 啊哈哈,有趣的是它确实有效,但几个小时前我真的错过了它。我知道为什么,所以可以为我澄清几件事吗?第一:为什么当使用评论 const json = await res.json(); 而只是 return { data: res } 它给了我:Objects are not valid as a React child (found: [object Response]). If you meant to render a collection of children, use an array instead. in div (at another.js:4) in Page in Container in App in Context.Provider in Context.Provider in Context.Provider in Context.Provider
    • 我应该每次都将收到的来自fetch的数据转换成json吗?
    • 对于第二个问题,是的,您应该每次都使用.json() 转换接收到的数据。
    猜你喜欢
    • 2019-10-12
    • 2019-10-04
    • 2019-03-01
    • 2020-02-04
    • 2021-08-06
    • 2019-07-18
    • 1970-01-01
    • 2018-08-31
    • 2021-03-14
    相关资源
    最近更新 更多