这是我的代码到目前为止,根据“基本”费率和选定日期提取历史货币数据。有没有办法显示“货币名称”和“费率”列中返回的数据?到目前为止,我的代码位于此处:http://codepen.io/co851002/pen/PWqVwr
var date = '2017-01-06'
var base = 'USD'
var API_request = 'https://api.fixer.io/' + date + '?base=' + base;
var App = React.createClass({
getInitialState: function() {
return {
rates: []
}
},
componentDidMount: function() {
var th = this;
this.serverRequest =
axios.get(API_request)
.then(function(result) {
console.log(result.data.rates)
th.setState({
rates: result.data.rates
});
})
},
componentWillUnmount: function() {
this.serverRequest.abort();
},
render: function() {
var self = this;
return (
<div className="table">
<table >
<thead>
<tr>
<th>Currency</th>
<th>Value</th>
</tr>
</thead>
<tbody>
<tr>
<td>Currency goes here</td>
<td>Value goes here</td>
</tr>
</tbody>
</table>
</div>
)
}
});
React.render(<App />, document.querySelector("#root"));
答案 0 :(得分:1)
只需对数据使用Object.keys(rates)
.map
,并在每次迭代时返回所需的DOM元素。
Object.keys()方法返回给定对象拥有的可枚举属性的数组......
换句话说,Object.keys
将为您提供一个包含所有不同货币类型的数组:
["AUD", "BGN", "BRL", ...]
现在您可以使用Array.prototype.map
迭代数组并返回需要返回的内容。
map()方法创建一个新数组,其结果是在此数组中的每个元素上调用提供的函数。
{Object.keys(rates).map(function(value, idx) {
return <tr key={idx}>
<td>{value}</td>
<td>{rates[value]}</td>
</tr>
})}
这是一个例子。
var date = '2017-01-06'
var base = 'USD'
var API_request = 'https://api.fixer.io/' + date + '?base=' + base;
var App = React.createClass({
getInitialState: function() {
return {
rates: []
}
},
componentDidMount: function() {
var th = this;
this.serverRequest =
axios.get(API_request)
.then(function(result) {
console.log(result.data.rates)
th.setState({
rates: result.data.rates
});
})
},
componentWillUnmount: function() {
this.serverRequest.abort();
},
render: function() {
var self = this;
var rates = this.state.rates;
return (
<div className="table">
<table>
<thead>
<tr>
<th>Currency</th>
<th>Value</th>
</tr>
</thead>
<tbody>
{Object.keys(rates).map(function(value, idx) {
return <tr key={idx}>
<td>{value}</td>
<td>{rates[value]}</td>
</tr>
})}
</tbody>
</table>
</div>
)
}
});
ReactDOM.render(<App />, document.querySelector("#root"));
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/axios/0.8.1/axios.min.js"></script>
<div id="root"></div>
&#13;