【问题标题】:How to extract data from json and pass as props in Next.js如何从 json 中提取数据并在 Next.js 中作为 props 传递
【发布时间】:2021-03-03 17:19:15
【问题描述】:

我目前陷入这种情况:

  1. 我需要将props 传递给组件以填充DataGrid
  2. 因此,我使用getStaticProps 从 API 获取 JSON 数据,然后作为道具返回。
  3. 但是,我只需要 JSON 文件的每个条目中的 3 个属性,并且我必须仅将这 3 个属性作为道具传递给 DataGrid

问题:如何将每个条目(大约 50 个条目)中的 3 个 json 属性提取到我自己的 JSON 对象中。然后,将 JSON 对象作为 props 返回?

我当前的代码:

  export async function getStaticProps(){
  const res = await fetch ('https://api.link.example')
  const data = await res.json()

  return{
    props: {
      data
    },
  }
}

组件代码

export default function dashboard({data}){
return (
    <Layout>
    <div style={{ height: 400, width: '100%' }}>
        <DataGrid rows={data}  /*material UI kit*/
        columns={columns} 
        pageSize={5} 
        checkboxSelection 
        disableSelectionOnClick="true" />
    </div>
    </Layout>
)

}

示例 JSON

[{"total": 121227292170, 
"high": 74886, (require)
"low": 71316, (require)
"price": 2847.93, (require)
"price_change": 3.95671,},

{"total": 121227292170, 
"high": 74886, (require)
"low": 71316, (require)
"price": 2847.93, (require)
"price_change": 3.95671,}]

【问题讨论】:

    标签: json reactjs next.js


    【解决方案1】:

    这是你想要的吗?

    let data = await res.json()
    
    data = data.map(item => {
        
         const { price, high, low } = item
         return { price, high, low }
    })
    

    .map 将遍历所有对象,return 语句将只返回你想要的键。

    【讨论】:

    • 你是个救命稻草!
    猜你喜欢
    • 2021-05-29
    • 1970-01-01
    • 1970-01-01
    • 2021-09-22
    • 1970-01-01
    • 2017-09-15
    • 2021-12-22
    • 1970-01-01
    • 2019-06-04
    相关资源
    最近更新 更多