【发布时间】:2017-10-25 14:52:56
【问题描述】:
我正在使用 React.js 制作应用程序。我使用 API 获取一些数据,并试图在列表中显示这些数据。目前,当我尝试遍历数据时收到以下错误。
对象作为 React 子级无效(找到:带有键 {USDUSD、USDEUR、USDCAD、USDAUD} 的对象)。如果您打算渲染一组子项,请改用数组或使用 React 附加组件中的 createFragment(object) 包装对象。检查`Exchange
的渲染方法
即使我将数据存储在数组中,也会出现此错误。
我检查了有一个与此错误相关的类似线程:Objects are not valid as a React child,但这些答案对我的情况没有帮助。
这是我的代码。
import React from 'react';
import axios from 'axios';
const baseUrl = 'http://apilayer.net/api/historical?'
const API_KEY = 'API_KEY'
const date = '2017-10-22';
const currencies = 'USD,EUR,CAD,AUD';
const format = 1;
export default class Exchange extends React.Component {
constructor(props) {
super(props);
this.state = {
item : []
};
}
componentDidMount(){
const url = `${baseUrl}${API_KEY}&date=${date}¤cies=${currencies}&format=${format}`
axios.get(url)
.then(({data}) => {
this.state.item.push(data.quotes);
this.setState({
item: this.state.item
});
})
.catch((err) => {})
console.log("item" + this.state.item)
}
render() {
const rate = this.state.item.map((element, index)=>{
console.log("element" + element)
return <div key={index}>
<p>{element}</p>
</div>
});
return (
<div>
<div>Exchange</div>
<ul>Today's rate
<li>{ rate }</li>
</ul>
</div>
)
}
}
【问题讨论】:
-
element不是字符串、数字或数组。 -
console.log('element', element)返回什么? -
是的,你是对的。我错误地粘贴了它,所以我现在编辑代码。我仍然收到同样的错误。
-
@ChaseDeAnda 它返回
element[object Object] -
好吧,这样就行不通了。您需要使用来自该对象的数据来呈现项目。对象中有哪些数据?在您的
componentDidMount中,data.quotes是什么?