React中多个AJAX请求的最佳实践?

时间:2017-09-26 14:44:41

标签: javascript ajax reactjs

我正在使用React开展一个个人项目,其中我想渲染一些组件,每个组件使用Yahoo的天气API来显示来自不同城市的数据。

最初,我正在映射包含我想要数据的城市的数组,将每个城市向下发送到发出AJAX请求的组件,结果是5-6个不同的组件,每个组件都自己调用。如果我只想渲染当前条件或几个不同城市的高低,那就行得很好。

但是我想使用React Router让用户能够点击一个城市,导致重新渲染显示该城市的详细信息和10天预测 only < / strong>即可。我遇到的问题是项目的当前结构。因为我正在映射父节点中的城市数组,所以我可以将其传递到API URL中,我无法渲染所有预测组件。

构建项目并制作AJAX请求的更好方法是,一个视图是多个天气组件,另一个是单个详细信息视图和该城市的10天预测?

class App extends Component {

 PLACES = [
   { city: "chattanooga", state: "tn"},
   { city: "easton", state: "md"},
   { city: "new york", state: "ny"},
   { city: "norfolk", state: "va"},
   { city: "milford", state: "de"},
   { city: "bangkok", state: null}
 ]

 render() {
   return (
     <div className="weather-container">
       {
         this.PLACES.map( (place, id) => {
           return <Weather key={place.city} id={id} city={place.city} 
                  state={place.state} />
         })
       }
     </div>
   )
  }
}

export default App

这是父组件映射到PLACES数组以呈现6 <Weather />个组件。然后在<Weather />组件中,我在componentDidMount()

中发出了我的AJAX请求
componentDidMount() {
    axios.get(`https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22${this.props.city}%2C%2$${this.props.state}%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys`)
    .then(res => {
      let data = res.data.query.results.channel;
      this.setState({ data : data });
    })
    .catch( (error) => {
      console.log(error);
    })
  }

感谢任何方向!

1 个答案:

答案 0 :(得分:0)

Weather组件中,您应该有<Link>个新组件,路线看起来像weather/:location:location表示法意味着您可以在此处接受任何内容,例如chattanooga。如果您需要通过城市和州,请执行weather/:city/:state此路线将接受您的参数,然后您可以使用这些路线重新调用您要查看的特定城市的API以及其内部的10天预测您的新组件。

您可以拨打this.props.match.params.locationthis.props.match.params.city等来访问新组件内的参数。