【问题标题】:Set variable with REST API data使用 REST API 数据设置变量
【发布时间】:2018-08-29 09:23:10
【问题描述】:

我从未使用过 REST api,并且无法弄清楚如何使用返回的 result.data 设置变量。我将 Meteor 与 ReactJs 一起使用,并且 console.log('countries', countries) 正在返回 undefinedconsole.log(result.data) 正在返回国家数据。

export default class CountryPage extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    const countries = HTTP.get('https://restcountries.eu/rest/v2/all', (err, result) => {
      console.log(result.data);
      return result.data;
    });
    console.log('countries', countries);
    return (
      <div>  
        <Input type="select" name="countrySelect" id="countrySelect">
          {countries.map(country => (
            <option>{country.name}</option>
          ))}
        </Input>
      </div>
    );
  }
}

【问题讨论】:

  • (注:未验证)据我所知,Wesgur 提供的答案是正确的,因为您没有正确处理 AJAX。但是,应该注意render 可能不适合拨打此类电话。将 AJAX 调用置于 componentDidMount 并使用结果设置状态
  • 不推荐使用 componentDidMount 吗? @vapurrmaid
  • 我以为是componentWillMount,但我有一段时间没有使用 React。 The documentation 似乎也表明了这一点:UNSAFE_componentWillMount(),虽然正常显示 componentDidMount - 所以我认为它仍然可以安全使用

标签: reactjs meteor


【解决方案1】:

在这里,我们使用生命周期方法componentDidMount 这是进行 API 调用和设置订阅的最佳位置

 export default class CountryPage extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
            countries: []
        }
      }
      componentDidMount() {
        HTTP.get('https://restcountries.eu/rest/v2/all', (err, result) => {
          this.setState({countries:result.data})
        });
      }
      render() {
        const {countries} = this.state;
        return (
          <div>  
            <Input type="select" name="countrySelect" id="countrySelect">
              {countries.map(country => (
                <option>{country.name}</option>
              ))}
            </Input>
          </div>
        );
      }
    }

【讨论】:

  • 不推荐使用 componentDidMount 吗?我阅读了文档,它说不要使用它。
  • @Paul,初始化状态
  • @bp123 UNSAFE_componentWillMount() 已弃用。
  • @bp123 看到我在这个问题上发表的评论 - 我认为你混淆了 componentWillMountcomponentDidMount
  • 谢谢。关于componentDidMount,您是对的。我想我把它弄混了。
【解决方案2】:

HTTP 请求是一个异步任务。你必须等待 API 的响应所以

export default class CountryPage extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    HTTP.get('https://restcountries.eu/rest/v2/all', (err, result) => {
        const countries = result.data;
        console.log('countries', countries);
        return (
          <div>  
            <Input type="select" name="countrySelect" id="countrySelect">
              {countries.map(country => (
                <option>{country.name}</option>
              ))}
            </Input>
          </div>
        );
    });
  }
}

【讨论】:

    猜你喜欢
    • 2020-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-06
    • 2017-08-20
    相关资源
    最近更新 更多