【问题标题】:React - Cant access rates from state (api call) [duplicate]React - 无法从状态访问速率(api调用)[重复]
【发布时间】:2019-03-26 06:18:12
【问题描述】:
import React, { Component } from 'react';
import axios from 'axios';

class SearchCurrency extends Component {
  constructor() {
    super();
    this.state = {
      data: {}
    }
  }

  componentDidMount() {
    axios
      .get('http://data.fixer.io/api/latest?access_key=b0ab4945712b358052a8fc54d02e7b3d&base=EUR&symbols=USD,CAD,CHF,GBP,AUD')
      .then(res => 
          this.setState({
            data: res.data
          })
        )
      .catch(err => console.log(err))

  //api call here

  }
  render() {

由于某种原因,我无法访问州内的速率 obj

 const test = this.state.data.rates

  i try to map through obj here
  // const obj = Object.keys(test).map(i => test[i])

    console.log(test);

    // const map = test.map(i => <li>{i}</li>)
    return (
      <div>
        {/* {map} */}
      </div>
    )
  }
}
export default SearchCurrency;

谢谢

【问题讨论】:

    标签: javascript reactjs api


    【解决方案1】:

    渲染在此可用之前被调用,并引发错误。确保使用 if 来保护它,如下所示:

    if (!this.state || this.state.data) {
       return null;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-19
      • 2021-01-15
      • 2021-11-13
      • 2020-01-10
      • 2014-11-21
      • 2020-11-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多