【问题标题】:How do I render an array within an object of array in React Native如何在 React Native 中的数组对象中渲染数组
【发布时间】:2019-06-01 18:21:24
【问题描述】:

下面的代码显示了 2 个应该将组件渲染到屏幕的函数。当我通过数组进行映射时,组件会呈现。问题是当我尝试通过数组中的对象内的数组进行映射时,组件不会呈现。

假设我们有这个数据集:

const categories = [
  {
    title: "Burgers",
    items: [
      {
        item_number: 0,
        name: "Cheese Burgers"
      },
      {
        item_number: 1,
        name: "Double Cheese Burgers"
      },
      {
        item_number: 2,
        name: "Triple Cheese Burgers"
      }
    ]
  }
];

然后我们就有了这个渲染函数:

 render() {
    const { backgroundImage, menuIndex } = this.props.screenProps;

    return (
      <View>
        {/*THIS DOES RENDER*/}
        {categories ? (
          categories.map((category, i) => (
            <Card key={i} image={backgroundImage}>
              <Text style={{ marginBottom: 10 }}>{category.title}</Text>
            </Card>
          ))
        ) : (
          <ActivityIndicator style={styles.center_screen} />
        )}

        {/*THIS DOES NOT RENDER*/}
        {categories ? (
          categories[menuIndex].items.map((item, i) => {
            <View key={i}>
              {console.warn(item.name)}
              <Text>{item.name}</Text>
            </View>;
          })
        ) : (
          <ActivityIndicator style={styles.center_screen} />
        )}
      </View>
    );
  }
}

变量“类别”是从 API 调用的,当它在路由中时,活动指示器会显示。当它不为空时,我可以映射数组并显示每个对象的文本。但是,当我尝试通过数组对象内的数组进行映射时,我无法将文本呈现到屏幕上。当我将警告记录到屏幕上时,我可以看到“item.name”,但在文本组件中看不到。

这是如何以及为什么会发生的?

【问题讨论】:

  • 你检查过 categories[menuInde​​x] 是否返回一个对象吗?
  • 是的,我可以在 YellowBox 组件中看到它,但在 Text 组件中看不到。
  • 您是否尝试删除黄色框?只是一种预感。可能已停止渲染。
  • 当你有一个箭头函数并开始一个块{}语句,没有隐式返回,它需要一个显式的return语句,你可以,替换括号中的花括号使隐式返回起作用,或显式使用return 语句...
  • 非常好!我现在刚换了。

标签: javascript arrays reactjs react-native ecmascript-6


【解决方案1】:

您在地图中缺少返回语句

改变

categories[menuIndex].items.map((item, i) => {
            <View key={i}>

到

categories[menuIndex].items.map((item, i) => {
       return <View key={i}>

当您有自定义表达式(多行表达式)时,您需要在迭代器中编写一些自定义逻辑,因此您希望将其包装到花括号 {},这样您的映射回调期望您返回结果。

Demo

【讨论】:

    【解决方案2】:
    {/*THIS DOES NOT RENDER*/}
    {categories ? (
      categories[menuIndex].items.map((item, i) => {
        return (
         <View key={i}>
          {console.warn(item.name)}
          <Text>{item.name}</Text>
        </View>
        );
      })
    ) 
    

    您是否尝试过返回 return 您的视图?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-19
      • 1970-01-01
      • 2020-03-03
      • 2019-11-15
      • 2019-09-13
      • 1970-01-01
      相关资源
      最近更新 更多