我正在设置一个带有Rails后端的React应用程序。我得到的错误“对象是无效的React子(发现:对象与键{id,名称,信息,created_at, updated_at})。如果你想呈现一组子元素,请使用数组。”

这是我的数据:

[
    {
        "id": 1,
        "name": "Home Page",
        "info": "This little bit of info is being loaded from a Rails 
        API.",
        "created_at": "2018-09-18T16:39:22.184Z",
        "updated_at": "2018-09-18T16:39:22.184Z"
    }
]

我的代码如下:

import React from 'react';

class Home extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      error: null,
      isLoaded: false,
      homes: []
    };
  }

  componentDidMount() {
    fetch('http://localhost:3000/api/homes')
      .then(res => res.json())
      .then(
        (result) => {
          this.setState({
            isLoaded: true,
            homes: result
          });
        },
        // error handler
        (error) => {
          this.setState({
            isLoaded: true,
            error
          });
        }
      )
  }

  render() {

    const { error, isLoaded, homes } = this.state;

    if (error) {
      return (
        <div className="col">
          Error: {error.message}
        </div>
      );
    } else if (!isLoaded) {
      return (
        <div className="col">
          Loading...
        </div>
      );
    } else {
      return (
        <div className="col">
          <h1>Mi Casa</h1>
          <p>This is my house y'all!</p>
          <p>Stuff: {homes}</p>
        </div>
      );
    }
  }
}

export default Home;

我做错了什么?


当前回答

就我而言,我做到了

<IonListHeader>
  <IonLabel>
     Order {{index}}
  </IonLabel>
</IonListHeader>

而不是

<IonListHeader>
  <IonLabel>
     Order {index}
  </IonLabel>
</IonListHeader>

双花括号。

其他回答

我也有同样的问题,然后我意识到我犯了有史以来最愚蠢的错误。我让我的组件是异步的,我的意思是我使用了async关键字,就像这样

const ComponentName = async () => {
  return <>
   <div>This a WRONG component</div>
 </>
}

然后,在经历了很多头疼和祈祷之后,我意识到我的愚蠢错误,并删除了async。

const ComponentName = () => {
  return <>
   <div>This a WRONG component</div>
 </>
}

使用时刻格式,因为那是日期…转换为日期格式… 时刻(array_list_item.close_date) .format(“;”)}

注意:React不会在map函数中显示这种类型的日期格式

“created_at”:“2018 - 09 - 18 t16:39:22.184z”,

我也遇到过同样的问题,但现在我很高兴解决了这个问题。

NPM I core-js 把这一行放到index.js文件的第一行。 进口core-js

在设置为UseState之前,我在使用BigNumber库的值时出现了这个错误:

const { toBN } = web3.utils;
...
 setOwner0Balance(toBN(await getBalance(owner0)));

我面对的正是这个错误。在追踪这个问题的根本原因时,我发现FRONTEND代码(React)正在调用API,并通过访问该响应的某些属性在页面上显示响应! 在这种情况下,有两种情况

该属性在后台的响应中不存在(它会抛出不同的错误) 或 来自后端响应的属性是一个复杂的对象(对象中的对象),我们的前端React组件试图访问它, 但是无法读取,因为React需要一个STRING(通过直接访问特定的属性,例如Object.property)或数组。(这种情况下)

所以我们收到这个错误,因为React期待STRING但得到了对象(因为你在对象内部传递object)。

请检查发送响应的后端逻辑(API)。