React Native中的数组渲染(未定义不是对象) [英] Array rendering in React Native (undefined is not an object)

查看:87
本文介绍了React Native中的数组渲染(未定义不是对象)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在渲染数据数组。它可以与map函数配合使用,但是如果我尝试明智地调用item,则会出现错误。
未定义不是对象(正在评估'data [0] .uri')

I am rendering a array of data. It works fine with map function but if I try to call item wise it gives an error. Undefined is not an object (evaluating 'data[0].uri')

这不起作用

render () {
    const data  = this.state.data;
    const selectedIndex = this.state.selectedIndex;
    return (
      <View style={styles.text}>

            <Card
              title="Profiling Question "
              image={{ uri: data[0].uri }}
            >
              <Text style={{ marginBottom: 10 }}>
                {data[0].text}
              </Text>
              <Button
                onPress={this.updateIndex}
              />
            </Card>

      </View>
    );
  }

但这可以正常工作:

return (
      <View style={styles.text}>
      {data.map((item) => {
        return (
            <Card
              title="Profiling Question "
              image={{ uri: item.question_image }}
            >
              <Text style={{ marginBottom: 10 }}>
                {item.question_text}
              </Text>
              <Button
                onPress={this.updateIndex}
              />
            </Card>
          )})}
      </View>
    );

我希望一次只在屏幕上渲染一个项目。用户单击按钮后,将渲染第二个项目。

I wish to render only ONE item at a time on screen. Once user clicks button then second item renders.

推荐答案

检查数据的空值。如果值是null或未设置,则不显示任何内容,否则显示数据。

check for the empty value of data. if value is null or not set then display nothing otherwise display data.

render () {
    const data  = this.state.data;
    const selectedIndex = this.state.selectedIndex;
    return (
      <View style={styles.text}>

            <Card
              title="Profiling Question "
              image={{ uri: data[0] ? data[0].uri: null }}
            >
              <Text style={{ marginBottom: 10 }}>
                {data[0] ? data[0].text: ''}
              </Text>
              <Button
                onPress={this.updateIndex}
              />
            </Card>

      </View>
    );
  }

这篇关于React Native中的数组渲染(未定义不是对象)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆