首页 > 解决方案 > 在 Next JS 中访问 JSON 对象中的数据

问题描述

我有一个包含另一个对象的对象。访问内部对象的属性不起作用。

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'}
}

标签: javascriptjsonnext.js

解决方案


你要回来{props: {data}} 所以它必须是props.data.state.name


推荐阅读