React Native 中的数组渲染(未定义不是对象)

IT技术 arrays reactjs react-native
2021-05-17 16:09:57

我正在渲染一组数据。它适用于 map 函数,但如果我尝试明智地调用 item ,则会出现错误。 未定义不是对象(评估'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>
    );

我希望一次只在屏幕上渲染一个项目。一旦用户单击按钮,就会呈现第二个项目。

2个回答

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

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>
    );
  }

您可以使用条件渲染来说明数据为空,以确保仅在数据填充后才渲染

render() {
    const data          = this.state.data;
    const selectedIndex = this.state.selectedIndex;
    return (
        <View style={styles.text}>
            {data && data[selectedIndex] &&
            <Card
                title="Profiling Question "
                image={{uri: data[selectedIndex].question_image}}
            >
                <Text style={{marginBottom: 10}}>
                    {data[selectedIndex].question_text}
                </Text>
                <Button
                    onPress={this.updateIndex}
                />
            </Card>
            }
        </View>
    );
}