类型错误:未定义不是对象(评估 '_this.state.data)

时间:2021-02-03 08:20:31

标签: javascript reactjs react-native

当我尝试关闭模态窗口时发生错误。在“关闭”按钮上。错误说 _this.state.data [imageKey] .urls' 不是对象,但我传递了字符串。

我从自定义 API 端点接收 JSON。我能够遍历 JSON 并输出一些数据,但问题在于对图像的字符串引用。我收到错误:

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  TouchableWithoutFeedback,
  Dimensions,
  Modal,
  ScrollView,
} from 'react-native';
import ImageElement from './component/ImageElement';
export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      modalVisible: false,
      data: [],
    };
  }

  componentDidMount() {
    fetch('https://api.unsplash.com/photos/?client_id=cf49c08b444ff4cb9e4d126b7e9f7513ba1ee58de7906e4360afc1a33d1bf4c0')
      .then((response) => response.json())
      .then((data) => {
        this.setState({
          data: data,
        });
      });
  }

  // getImage() {
  //   return this.state.modalImage
  // }

  setModalVisible = (visible, imageKey) => {
    this.setState({ modalImage: this.state.data[imageKey].urls.raw });
    this.setState({ modalVisible: visible });
  };

  render() {
    let images = this.state.data.map((val, key) => {
      return (
        <TouchableWithoutFeedback
          key={key}
          onPress={() => {
            this.setModalVisible(true, key);
          }}
        >
          <View style={styles.imagewrap}>
            <ImageElement
              author={{ url: val.user.profile_image.small }} // фото автора
              imgsource={{ url: val.urls.small }} // работа автора
              authorNameProp={val.user.name} // имя автора
            ></ImageElement>
          </View>
        </TouchableWithoutFeedback>
      );
    });
    return (
      <ScrollView>
        <View style={styles.container}>
          <Modal
            style={styles.modal}
            animationType={'fade'}
            transparent={true}
            visible={this.state.modalVisible}
            onRequestClose={() => {}}
          >
            <View style={styles.modal}>
              <Text
                style={styles.text}
                onPress={() => {
                  this.setModalVisible(false);
                }}
              >
                Close
              </Text>
              <ImageElement imgsource={{ url: this.state.modalImage }}></ImageElement>
            </View>
          </Modal>
          {images}
        </View>
      </ScrollView>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'row',
    flexWrap: 'wrap',
    backgroundColor: 'grey',
    overflow: 'scroll',
  },
  imagewrap: {
    margin: 5,
    padding: 2,
    height: Dimensions.get('window').height / 2 - 60,
    width: Dimensions.get('window').width / 2 - 10,
  },
  modal: {
    flex: 1,
    padding: 10,
    backgroundColor: 'rgba(0,0,0, 0.9)',
  },
  text: {
    color: '#fff',
    zIndex: 20,
    position: 'absolute',
    top: 50,
    right: 30,
    fontSize: 20,
  },
  user: {
    color: '#fff',
    zIndex: 20,
    position: 'absolute',
    top: 20,
    left: 10,
  },
});

AppRegistry.registerComponent('ImageGallery', () => ImageGallery);

1 个答案:

答案 0 :(得分:0)

问题

似乎您错过了在关闭处理程序 this.setModalVisible(false) 中传递索引,imageKey 未定义,因此 this.state.data[undefined] 未定义并在您更深入地访问嵌套属性时抛出错误。

解决方案

根据 visible 值有条件地访问数据值。关闭模态时清除 modalImage 状态。

setModalVisible = (visible, imageKey) => {
  this.setState({
    modalImage: visible ? this.state.data[imageKey].urls.raw : null,
    modalVisible: visible,
  });
}

或者,您也可以使用 Optional Chaining 为您做空检查。

setModalVisible = (visible, imageKey) => {
  this.setState({
    modalImage: this.state.data[imageKey]?.urls?.raw,
    modalVisible: visible,
  });
}