【问题标题】:Best way to get HTTP data and handle a 404?获取 HTTP 数据和处理 404 的最佳方法?
【发布时间】:2017-04-28 21:53:27
【问题描述】:

我对 React 还很陌生,所以我不知道获取数据的最佳方法。我有一个像 /country/japan 这样的页面 URL,这是我的组件:

var Country = React.createClass({

  componentDidMount: function() {
    var _this = this,
        country = _this.props.params.country;

    Axios.get('http://URL/?search=' + country)
      .then(function(result) {
        _this.setState({
          country: result.data[0]
        });
      });
  },

  componentWillUnmount: function() {
    this.serverRequest.abort();
  },

  render: function() {
    var country = this.state.country;
    return (
      <div>
        <h1>{country.name}</h1>
      </div>
    );
  }

});

我似乎无法访问国家/地区数据。这样做的正确方法是什么?另外,您将如何触发 404?

【问题讨论】:

  • 通常我们只使用.fetch,但是使用像 Axios 这样的 AJAX 库就可以了。查看他们的文档以了解如何处理请求失败。可能是.catch.then 之后。

标签: reactjs axios


【解决方案1】:

我想说首先要了解展示组件和容器组件之间的区别。

演示组件:

  • 关心事物的外观。
  • 内部可能包含展示组件和容器组件,并且通常有一些自己的 DOM 标记和样式。通常允许通过 this.props.children 进行收容。
  • 不依赖于应用程序的其余部分,例如 Flux 操作或存储。
  • 不要指定如何加载或更改数据。
  • 仅通过 props 接收数据和回调。
  • 很少有自己的状态(当他们有时,它是 UI 状态而不是 数据)。
  • 除非需要状态,否则被编写为功能组件,
    生命周期挂钩或性能优化。
  • 示例:页面、边栏、故事、用户信息、列表。

容器组件:

  • 关心事物的运作方式。
  • 内部可能同时包含展示组件和容器组件**,但 通常没有任何自己的 DOM 标记,除了一些 包装 div,并且永远不会有任何样式。
  • 向展示容器或其他容器提供数据和行为 组件。
  • 调用 Flux 操作并将这些操作作为回调提供给 展示组件。
  • 通常是有状态的,因为它们往往用作数据源。
  • 通常使用高阶组件生成,例如 connect() 来自 React Redux、来自 Relay 的 createContainer() 或 Container.create() 来自 Flux Utils,而不是手写。
  • 示例:UserPage、FollowersSidebar、StoryContainer、 已关注用户列表。

您可以查看更多here。这将帮助您了解如何触发 api 调用(它应该在容器中)。

所以现在来看看你的代码。我会说将您的 api 代码移动到容器中并在容器内调用您的组件。

var CountryContainer = React.createClass({


 componentDidMount: function() {
       var _this = this,
        country = _this.props.params.country;

    axios.get('http://URL/?search=' + country)
      .then(function(result) {
         //200-300 response codes
         //update you state here with say variable data
      .catch(function(error){
          //400+ response codes
        }
      });

  componentWillUnmount: function() {
    this.serverRequest.abort();
  },

  render: function() {
    return (
      <Country data={this.state.data} />
    );
  }

});

我建议你去 axios 文档。他们清楚地提到了 API 调用何时失败以及如何处理它:)

【讨论】:

    猜你喜欢
    • 2010-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-17
    • 1970-01-01
    • 2020-11-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多