简体   繁体   English

React / Redux:从浏览器获取数据后如何调用API?

[英]React/Redux: how to call an API after getting data from the browser?

My React app is supposed to display nearby shops to each user depending on their location. 我的React应用程序应该根据每个用户的位置向他们显示附近的商店。

What I'm trying to do is to get the latitude/longitude by window.geolocation in the componentDidMount() in which I'll call a REST API with the latitude/longitude as params to retrieve nearby shops. 我想做的是通过componentDidMount()中的window.geolocation获取纬度/经度,在其中我将使用纬度/经度作为参数的REST API来检索附近的商店。

I'm just trying to figure out how to organize and where to put the logic. 我只是想弄清楚如何组织以及将逻辑放置在何处。

The idea is that you should try to use React's state before reaching for redux. 这个想法是您应该在到达redux之前尝试使用React的状态。 It's both simpler and keeps as much of the state local as possible. 它既简单,又保持尽可能多的本地状态。

The React state stores the status of the API call (not made yet, success or failure) and the corresponding information about success ( results ) or failure ( errorMessage ). React状态存储API调用的状态(尚未完成,成功或失败)以及有关成功( results )或失败( errorMessage )的相应信息。 The important point is that your render function must explicitly handle all 3 cases. 重要的一点是, render函数必须显式处理所有3种情况。

 class NearbyShops extends React.Component { constructor(props) { super(props); this.state = { queryStatus: 'initial', results: [], errorMessage: '', } } async componentDidMount() { try { const results = await fetch('you.api.url/here'); this.setState(prevState => ({...prevState, results, queryStatus: 'success'})) } catch (e) { this.setState(prevState => ({...prevState, queryStatus: 'failure', errorMessage: e})) } } render() { const {results, queryStatus, errorMessage} = this.state; if (queryStatus === 'success') { return ( <div>{/* render results here */}</div> ) } else if (queryStatus === 'failure') { return ( <div>{errorMessage}</div> ) } else { return ( <div>Loading nearby shops...</div> ) } } } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM