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;
谢谢
答案 0 :(得分:1)
渲染器在此可用之前被调用,并引发错误。确保使用if来保护它,就像这样:
if (!this.state || this.state.data) {
return null;
}