【问题标题】:Render JSON data from API call in react在反应中渲染来自 API 调用的 JSON 数据
【发布时间】:2019-04-26 08:44:11
【问题描述】:

使用谷歌地图 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"
}

【问题讨论】:

    标签: reactjs api geolocation


    【解决方案1】:

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

    在 componentDidMount 中最好使用 then 并捕获错误

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

    }

    【讨论】:

      【解决方案2】:

      首先,你必须这样做:

       <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 : 对不起我的英语不好;)

      【讨论】:

        【解决方案3】:

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

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

        【讨论】:

        • 添加了错误消息处理程序,但现在它只是一个空白页面。虽然没有更多未定义的错误
        • 首先,将 if (!loaded) 放在 if (error) 之前。这是逻辑顺序。此外,将 state.error 初始化为 false。然后,按照此处的说明检查错误:stackoverflow.com/a/38236296/5532513
        猜你喜欢
        • 2019-10-07
        • 2020-09-05
        • 1970-01-01
        • 2021-03-20
        • 2020-06-28
        • 2018-06-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多