从API调用中渲染JSON数据

时间:2018-11-23 18:55:20

标签: reactjs api geolocation

使用Google Maps API在应用程序上使用Reactjs进行地理定位。我现在的目标是将整个JSON数据简单地呈现到窗口(稍后将使用)。没有错误,但没有任何内容呈现到页面。我是否尝试不正确地访问数据?

class App extends Component {
  constructor () {
    super();
    this.state = {
      isLoaded: false,
      results: {}
    };
  }

  componentDidMount() {
    fetch(geo_url)
    .then(res => res.json())
    .then(
      (result) => {
        this.setState({
          isLoaded: true,
          results: result.results
        });
      },
      (error) => {
        this.setState({
          isLoaded: true,
          error
        });
      }
    )
  }


  render() {
    const {error, isLoaded, results} = this.state;
      if (error) {
        return <div>Error: {error.message} </div>;
      } else if (!isLoaded) {
        return <div>Loading...</div>;
      } else {
      return (
        <div className="App">
          Location Data:
          {results.geometry}
        </div>
      );
  }
  }
}

以下是我尝试访问的JSON示例:

{
    "results": [
        {
            "address_components": [
                {
                    "long_name": "1600",
                    "short_name": "1600",
                    "types": [
                        "street_number"
                    ]
                },
                {
                    "long_name": "Amphitheatre Parkway",
                    "short_name": "Amphitheatre Pkwy",
                    "types": [
                        "route"
                    ]
                },
                {
                    "long_name": "Mountain View",
                    "short_name": "Mountain View",
                    "types": [
                        "locality",
                        "political"
                    ]
                },
                {
                    "long_name": "Santa Clara County",
                    "short_name": "Santa Clara County",
                    "types": [
                        "administrative_area_level_2",
                        "political"
                    ]
                },
                {
                    "long_name": "California",
                    "short_name": "CA",
                    "types": [
                        "administrative_area_level_1",
                        "political"
                    ]
                },
                {
                    "long_name": "United States",
                    "short_name": "US",
                    "types": [
                        "country",
                        "political"
                    ]
                },
                {
                    "long_name": "94043",
                    "short_name": "94043",
                    "types": [
                        "postal_code"
                    ]
                }
            ],
            "formatted_address": "1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA",
            "geometry": {
                "location": {
                    "lat": 37.422617,
                    "lng": -122.0853839
                },
                "location_type": "ROOFTOP",
                "viewport": {
                    "northeast": {
                        "lat": 37.4239659802915,
                        "lng": -122.0840349197085
                    },
                    "southwest": {
                        "lat": 37.4212680197085,
                        "lng": -122.0867328802915
                    }
                }
            },
            "place_id": "ChIJ2eUgeAK6j4ARbn5u_wAGqWA",
            "plus_code": {
                "compound_code": "CWF7+2R Mountain View, California, United States",
                "global_code": "849VCWF7+2R"
            },
            "types": [
                "street_address"
            ]
        }
    ],
    "status": "OK"
}

3 个答案:

答案 0 :(得分:1)

第一次渲染发生在检索结果之前。检查render()结果是否已经存在。如果没有,则显示“正在加载”消息。

除此之外,修复尝试检索数据时的错误处理。您正在设置未定义的state.error变量。然后,在渲染中,如果加载完成但显示错误,则显示一条错误消息。

答案 1 :(得分:0)

首先,您必须做:

 <div className="App">
     {this.state.results.geometry}
  </div>

     render() {
          const {results} = this.state
          return (
            <div className="App">
              {results.geometry}
            </div>
          );
      }
}

但是就像@Yossi所说的那样,您的结果未在第一次渲染中定义。这就是为什么您有:“结果未定义”。您可以使用“ lodash”强制渲染。即使我不知道这是一个好习惯,它也有效

您可以测试:

import _ from 'lodash';

     render() {
          const {results} = this.state
          return (
          {!_.isEmpty(results) && 
            <div className="App">
              {results.geometry}
            </div>             
            }

          );
      }

应该可以用:)

PS:对不起,我的英语不好;)

答案 2 :(得分:0)

您可以在状态中设置错误密钥:false。

然后在componentDidMount中更好地使用它并捕获错误

  componentDidMount() {
fetch(geo_url)
.then(res => res.json())
.then(
  (result) => {
    this.setState({
      isLoaded: true,
      results: result.results
    });
  },
  (error) => {
    this.setState({
      isLoaded: true,
      error
    });
  }
).catch(error) {
   this.setState({
   isLoaded: true,
   error
  })
 }

}