【问题标题】:accessing data from a nested Json从嵌套的 Json 访问数据
【发布时间】:2019-09-23 03:52:09
【问题描述】:

我有一个对象,稍后将替换为 JSON 响应结构,如下所示,我将其作为道具传递,在子组件中我希望通过“值”映射来呈现数据。

App.js

“data”: {
         “title”: {
           “text”: “”
         },
         “subtitle”: {
           “text”: “”
         },
         “renderable”: [
           {
             “title”: {
               “text”: “”
             },
             “sub_title”: {
               “text”: “”
             },
             “values”: [
               {
                 “id”: “1”,
                 “title”: {
                   “text”: “”
                 },
                 “subtitle”: {
                   “text”: “”
                 },
                 “price_tag”: {
                   “text”: “Rs 99"
                 },
                 “preselected”: “true”
               },
               {
                 “id”: “2",
                 “title”: {
                   “text”: “”
                 },
                 “sub_title”: {
                   “text”: “”
                 },
                 “price_tag”: {
                   “text”: “Rs 199”
                 },
                 “preselected”: “false”
               },
             ]
           }
         ]
       }

class App extends React.Component {
  render() {
    return (
      <React.Fragment>
        <Demo options={data} />
      </React.Fragment>
    )
  }
}

我不确定如何在子组件中访问和映射可渲染内部的“值”(目前可渲染内部只有一个对象,但稍后会填充)。

【问题讨论】:

    标签: javascript json reactjs


    【解决方案1】:

    你的数据结构是

    数据(对象)-> 可渲染(对象数组)-> 值(数组)

    所以你会先做

    data.renderable...
    

    然后您可以映射数组并点击每个对象,其中包含值数组。

    data.renderable.map((obj) => obj.values)
    

    然后您可以映射 obj.values,但使用 .flatMap() 将所有项目放入一个一级数组中会更有意义。

    data.renderable.flatMap((obj) => obj.values.map((item) => item.id))
    

    【讨论】:

      【解决方案2】:

      示例 Demo 可以显示类似

      的数据
      class Demo extends React.Component {
      
      render(){
          const { data } = this.props;
          return (
              <div>
                  <h1>{data.title}</h1>
                  <h2>{data.subtitle</h1>
                  <ul>
                      {data.renderable.map(row => (
                          <h1>{row.title}</h1>
                          <h2>{row.subtitle</h1>
                              {row.values.map(item => (
                                  <li key={item.id}>
                                      {item.title}
                                      {item.subtitle}
                                      {item.price_tag}
                                  </li>
                              ))}
                      ))}
                  </ul>
              </div>
              )
          }
      }
      
      export default Demo;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-10-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-06-11
        • 2021-03-21
        相关资源
        最近更新 更多