首页 > 解决方案 > 通过 json 数组映射来渲染屏幕 React Native

问题描述

我有一个 json 解析数组保存为构造函数的 this.state 部分中的变量(保存为 this.state.accordionarr)。然后,我正在尝试呈现手风琴列表(来自 ANTD Mobile RN)。但是,当我尝试访问 this.state.accordionarr 时,我收到 TypeError undefined is not an object(评估 this.state.accordionarr)。但是,我知道该变量使用控制台日志保存了正确的 json 数组。这是我的代码:

这是我最初制作数组的部分

if (this.state.idofdate != null && this.state.idofdate != undefined && this.state.idofdate != "") {
      db.collection('entirelog').doc(this.state.idofdate).collection('meals').get().then(querySnapshot => {
        const yourDocuments = querySnapshot.docs.map((doc) => doc.data());
        this.setState({
          accordionarr: yourDocuments
        });
        console.log(this.state.accordionarr);
      })
      .catch(err => {
        alert(err);
      });
    }

这是this.state.accordionarr的console.log,没错。这是我想要的解析的json

Array [
  Object {
    "carbohydrate": 8,
    "id": 0,
    "name": "kimbap",
    "protein": 1111,
  },
  Object {
    "carbohydrate": 67,
    "id": 1,
    "name": "soup",
    "protein": 56,
  },
]

这是我尝试渲染和访问变量的地方。

function renderAccordion() {
      return this.state.accordionarr.map((item,index) => {
        return(
          <View key={index}>
            <Accordion
              onChange={this.onChange}
              activeSections={this.state.activeSections}
            >
              <Accordion.Panel header= {item.name}>
                <List>
                  <List.Item>{item.protein}</List.Item>
                  <List.Item>{item.carbohydrate}</List.Item>
                </List>
              </Accordion.Panel>
            </Accordion>
          </View>
        );
      });
    }

标签: jsonreactjsreact-nativeexpoantd

解决方案


推荐阅读