javascript - 在 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'}
}
解决方案
你要回来{props: {data}}
所以它必须是props.data.state.name
推荐阅读
- python - 为什么 FOR IN 代码在重复时循环遍历数组中的最后一个(Python)?
- android - 如何在 Delphi FMX Android 平台上通过 Sip 和 SipManager 拨打电话?
- sql - 当一个表ID存在于另一表的多个列中时,如何编写SQL JOIN查询以获取结果
- google-maps - 在谷歌地图上触发折线点击时更改折线颜色
- javascript - 无法将多个值/数据推送到 angular 2-tree
- javascript - 识别 div 中的字符并添加类 javascript
- jquery - 引导箱模式未设置“选定”选择列表项
- javascript - 我怎样才能让我的广告适合身体宽度
- jmeter - 无法使用 JMeter 测试脚本记录器记录在 Internet Explorer 中本地主机上运行的应用程序
- android - 显示 QWERTY 键盘时显示线性布局冲突