【问题标题】:Error in map function / Objects are not valid as a React child / React.js映射函数中的错误/对象作为 React 子项/React.js 无效
【发布时间】: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}&currencies=${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 是什么?

标签: reactjs loops


【解决方案1】:

由于每个quote 都是一个对象,您可以使用Object.keys() 循环遍历.map() 中的对象以显示每个值。

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;
const quotes = {
  USDUSD: 1,
  USDEUR: 0.850499,
  USDCAD: 1.26377,
  USDAUD: 1.280799
};

class Exchange extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      item: []
    };
  }

  componentDidMount() {
    //const url = `${baseUrl}${API_KEY}&date=${date}&currencies=${currencies}&format=${format}`
    //axios.get(url)
    //.then(({data}) => {
    this.setState({
      item: this.state.item.concat([quotes])
    });
    //})
    //.catch((err) => {})
    //console.log("item" + this.state.item)
  }

  render() {
    const rate = this.state.item.map((quotes, index) => {
      return Object.keys(quotes).map(key => {
        return (
            <div key = {key} >
              <p>{quotes[key]}</p>
            </div>
          )
      })
    });

    return ( 
      <div>
        <div>Exchange</div> 
        <ul> 
          Today 's rate
          <li> {rate} </li> 
        </ul>
     < /div>
    )
  }
}

ReactDOM.render( < Exchange / > , document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

【讨论】:

  • 非常感谢您提供代码 sn-p 的答案。它与我的项目完美配合。我不知道object.key()
  • 很高兴你能成功!将来我们还会有Object.values(obj),它将返回一个包含所有值的数组,非常棒!
猜你喜欢
  • 2021-04-06
  • 2020-08-26
  • 2020-04-04
  • 2019-07-23
  • 2022-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多