【问题标题】:React/Redux: how to call an API after getting data from the browser?React/Redux:从浏览器获取数据后如何调用 API?
【发布时间】:2018-03-23 00:49:42
【问题描述】:

我的 React 应用应该根据每个用户的位置向他们显示附近的商店。

我要做的是通过componentDidMount() 中的window.geolocation 获取纬度/经度,我将在其中调用以纬度/经度为参数的REST API 来检索附近的商店。

我只是想弄清楚如何组织以及将逻辑放在哪里。

【问题讨论】:

  • 如果您想在首次加载站点时调用 API,您可以调用 componentDidMount。如果您想在更新数据后调用它,可以使用componentDidUpdate。您将使用Fetchaxios 进行ajax 调用。
  • 通常你会使用mapDispatchToProps来映射你想在componentDidMount中使用的方法SomeActionDispatcher到容器中的props。 SomeActionDispatcher 负责调度操作。
  • 异步动作可以在 redux 中间件中处理,你可以使用redux-thunk 这样你就可以调度一个动作来调用一个获取地理的函数,调度带有地理信息的动作,获取附近的商店, 解决后向商店发送操作。

标签: javascript node.js reactjs redux


【解决方案1】:

这个想法是你应该在使用 redux 之前尝试使用 React 的状态。它既简单又尽可能多地保持本地状态。

React 状态存储 API 调用的状态(尚未进行,成功或失败)以及有关成功(results)或失败(errorMessage)的相应信息。重要的一点是您的 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>
      )
    }
  }
}

【讨论】:

    猜你喜欢
    • 2020-10-20
    • 2021-09-27
    • 2018-11-17
    • 1970-01-01
    • 2017-10-18
    • 1970-01-01
    • 2020-06-04
    • 2021-06-05
    • 1970-01-01
    相关资源
    最近更新 更多