【问题标题】:Accessing an data in a JSON object in Next JS在 Next JS 中访问 JSON 对象中的数据
【发布时间】:2020-10-05 22:14:17
【问题描述】:

我有一个包含另一个对象的对象。无法访问内部对象的属性。

import React from 'react';
import Sidebar from "../../../components/Sidebar/Sidebar";
import {useRouter} from "next/router";

const News = (data:any) => {
    return (
        <>
            <div className="section section-main-page pt-0">
                <div className="container">
                    <div className="section section-panel">
                        <div className="section-panel-content">
                            <h1>{data.state.name}/{data.title}</h1>
                        </div>
                    </div>
                </div>
            </div>
        </>
    );
}

export default News;

export const getServerSideProps = async (context:any) =>{
    let data = await fetch(process.env.API_URL + '/' + context.query.state +'/news/' + 'test-news-article')
        .then( r => r.json() )
    console.log(data.state.name);
    return {props: {data}}
}

当我控制台数据时,它可以工作。但根据上面的代码,标题应该在的地方没有打印任何内容。在尝试访问data.state.name 时也是如此。我收到一个错误。

这是我的数据

{
    id: '1',
    title: 'Test News Article',
    summary: 'This is the summary',
    state: { id: '9', name: 'National'}
}

【问题讨论】:

  • console.log 显示的是什么?

标签: javascript json next.js


【解决方案1】:

您正在返回{props: {data}} 所以它必须是props.data.state.name

【讨论】:

    【解决方案2】:

    const News = (data:any) 更改为 const News = ({data}:any) 已修复此问题。

    【讨论】:

      猜你喜欢
      • 2012-06-29
      • 1970-01-01
      • 1970-01-01
      • 2021-09-22
      • 1970-01-01
      • 2023-04-11
      • 1970-01-01
      • 1970-01-01
      • 2021-12-21
      相关资源
      最近更新 更多