代码之家  ›  专栏  ›  技术社区  ›  bp123

使用REST API数据设置变量

  •  0
  • bp123  · 技术社区  · 8 年前

    result.data undefined 虽然 console.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>
        );
      }
    }
    
    2 回复  |  直到 8 年前
        1
  •  3
  •   Paul McLoughlin    8 年前

    这里,我们使用生命周期方法 componentDidMount

     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>
            );
          }
        }
    
        2
  •  0
  •   Wesgur    8 年前

    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>
            );
        });
      }
    }