gpt4 book ai didi

javascript - 如何将对象的属性和值映射到表?

转载 作者:行者123 更新时间:2023-11-29 23:56:22 25 4
gpt4 key购买 nike

到目前为止,这是我的代码,根据“基本”汇率和选定日期提取历史货币数据。有没有办法显示“货币名称”和“汇率”列中返回的数据?到目前为止,我的代码在下方和此处: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"));

最佳答案

只需使用 Object.keys(rates) 对您的数据进行 .map 并在每次迭代时返回所需的 DOM 元素。

Object.keys()

The Object.keys() method returns an array of a given object's own enumerable properties...

换句话说,Object.keys 将为您提供一个包含所有不同货币类型的数组,如下所示:

["AUD", "BGN", "BRL", ...]

现在您可以使用 Array.prototype.map 遍历数组并返回需要返回的内容。

Array.prototype.map()

The map() method creates a new array with the results of calling a provided function on every element in this array.

{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"));
<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>

关于javascript - 如何将对象的属性和值映射到表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41528660/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com