首页 > 解决方案 > 我有这个问题未定义不是一个对象(评估'this.state.dataSource.map')

问题描述

我想显示来自在线 json url 的地点列表。

import React, { Component } from "react";
import {
  View,
  StyleSheet,
  Dimensions,
  Image,
  StatusBar,
  TextInput,
  TouchableOpacity,
  Text,
  Button,
  Platform,
  Alert,
  FlatList,
  ActivityIndicator,
} from "react-native";

let url = "https://cz2006api.herokuapp.com/api/getAll";
let url2 = "";

export default class ClinicComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isLoading: true,
      dataSource: null,
    };
  }

  componentDidMount() {
    return fetch("https://cz2006api.herokuapp.com/api/getAll")
      .then((response) => response.json())
      .then((responseJson) => {
        this.setState({
          isLoading: false,
          dataSource: responseJson.data.data,
        });
      })
      .catch((error) => {
        console.log(error);
      });
  }
  render() {
    if (this.state.isLoading) {
      return (
        <View style={styles.container}>
          <ActivityIndicator />
        </View>
      );
    } else {
      let hospitals = this.state.dataSource.map((val, key) => {
        return (
          <View key={key} style={styles.item}>
            <Text>{val.name}</Text>
          </View>
        );
      });
      return (
        <View style={styles.item}>
          {/* <Text>Content Loaded</Text> */}
          {hospitals}
        </View>
      );
    }
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#fff",
    alignItems: "center",
    justifyContent: "center",
  },
  item: {
    flex: 1,
    alignSelf: "stretch",
    margin: 10,
    alignItems: "center",
    justifyContent: "center",
    borderBottomWidth: 1,
    borderBottomColor: "#eee",
  },
});

不幸的是,当我尝试通过 expo cli 运行它时出现错误,说 undefined is not an object enter image description here

任何人都可以帮助我吗?我只想有一个可滚动的医院列表。谢谢!Json 的 URL 在这里:https ://cz2006api.herokuapp.com/api/getAll

标签: jsonreact-native

解决方案


只需将您的初始状态更改为这样的

    this.state = {
      isLoading: true,
      dataSource: [],  // <-- here
    };

您的问题是您正在使用dataSource.map但在 api 调用期间您dataSource仍然保持 null 直到它得到响应,并且 null 对象没有属性map。这就是你的问题的原因。


推荐阅读