Javascript 对象作为 React 子对象无效。如果您打算渲染一组子项,请改用数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/52428879/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:59:32  来源:igfitidea点击:

Objects are not valid as a React child. If you meant to render a collection of children, use an array instead

javascriptarraysreactjs

提问by iChido

I am setting up a React app with a Rails backend. I am getting the error "Objects are not valid as a React child (found: object with keys {id, name, info, created_at, updated_at}). If you meant to render a collection of children, use an array instead."

我正在设置一个带有 Rails 后端的 React 应用程序。我收到错误消息“对象作为 React 子对象无效(找到:带有键 {id, name, info, created_at, updated_at} 的对象)。如果您打算渲染子项集合,请改用数组。”

This is what my data looks like:

这是我的数据的样子:

[
    {
        "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"
    }
]

My code is as follows:

我的代码如下:

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;

What am I doing wrong?

我究竟做错了什么?

采纳答案by Karl Taylor

Your data homesis an array, so you would have to iterate over the array using Array.prototype.map()for it to work.

您的数据homes是一个数组,因此您必须使用Array.prototype.map()遍历该数组才能使其工作。

return (
    <div className="col">
      <h1>Mi Casa</h1>
      <p>This is my house y&apos;all!</p>
      {homes.map(home => <div>{home.name}</div>)}
    </div>
  );

回答by utkarsh-k

I got the same error today but with a different scenario as compared to the scenario posted in this question. Hope the solution to below scenario helps someone.

我今天遇到了同样的错误,但与此问题中发布的场景相比,场景有所不同。希望以下场景的解决方案对某人有所帮助。

The renderfunction below is sufficient to understand my scenario and solution:

render下面的函数足以理解我的场景和解决方案:

render() {
    let orderDetails = null;
    if(this.props.loading){
        orderDetails = <Spinner />;
    }
    if(this.props.orders.length == 0){
        orderDetails = null;
    }
    orderDetails = (
        <div>
            {
                this.props.orders.map(order => (
                <Order 
                    key={order.id}
                    ingredient={order.ingredients}
                    price={order.price} />
                ))
            }
        </div>
    );
    return orderDetails;
}

In above code snippet : If return orderDetailsis sent as return {orderDetails}then the error posted in this question pops up despite the value of 'orderDetails' (value as <Spinner/>or nullor JSX related to <Order />component).

在上面的代码片段中:如果return orderDetails发送为return {orderDetails}那么尽管'orderDetails'的值(与组件相关的值<Spinner/>null或JSX <Order />),该问题中发布的错误仍然会弹出。

Error description: react-dom.development.js:57 Uncaught Invariant Violation: Objects are not valid as a React child (found: object with keys {orderDetails}). If you meant to render a collection of children, use an array instead.

错误描述:react-dom.development.js:57 Uncaught Invariant Violation: Objects are not valid as a React child (found: object with keys {orderDetails})。如果您打算渲染一组子项,请改用数组。

We cannot return a JavaScript object from a return call inside the render() method. The reason being React expects a component or some JSX or null to render in the UI and not some JavaScript object that I am trying to render when I use return {orderDetails}and hence get the error as above.

我们无法从 render() 方法内的返回调用返回 JavaScript 对象。原因是 React 期望在 UI 中呈现组件或某些 JSX 或 null,而不是我在使用时尝试呈现的某些 JavaScript 对象,return {orderDetails}因此会出现上述错误。

回答by Ula

I hope it will help someone else.

我希望它会帮助别人。

This error seems to occur also when you UNintentionally send an object to React child components.

当您无意中将对象发送到 React 子组件时,似乎也会发生此错误。

Example of it is passing to child component new Date('....') as follows:

它的示例是传递给子组件 new Date('....') 如下:

 const data = {name: 'ABC', startDate: new Date('2011-11-11')}
 ...
 <GenInfo params={data}/>

If you send it as value of a child component parameter you would be sending a complex Object and you may get the same error as stated above.

如果您将它作为子组件参数的值发送,您将发送一个复杂的对象,并且您可能会收到与上述相同的错误。

Check if you are passing something similar (that generates Object under the hood).

检查您是否正在传递类似的东西(在引擎盖下生成对象)。

回答by NoloMokgosi

Had the same issue, In my case I had 1. Parse the string into Json 2. Ensure that when I render my view does not try to display the whole object, but object.value

有同样的问题,在我的情况下,我有 1. 将字符串解析为 Json 2. 确保在渲染视图时不会尝试显示整个对象,而是 object.value

data = [
{
    "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"
}];
var jsonData = JSON.parse(data)

Then my view

然后我的看法

return (
<View style={styles.container}>
  <FlatList
    data={jsonData}
    renderItem={({ item }) => <Item title={item.name} />}
    keyExtractor={item => item.id}
  />
</View>);

Because I'm using an array, I used flat list to display, and ensured I work with object.value, not object otherwise you'll get the same issue

因为我使用的是数组,所以我使用了平面列表来显示,并确保我使用 object.value,而不是 object 否则你会遇到同样的问题

回答by Ali

In JavaScript, arrays and collections are different, although they are somewhat similar, but here the react needs an array. You need to create an arrayfrom the collectionand apply it.

在 JavaScript 中,数组和集合是不同的,虽然它们有些相似,但是这里的 react 需要一个数组。您需要创建一个arraycollection并应用它。

let homeArray = new Array(homes.length);
let i = 0

for (var key in homes) {
    homeArray[i] =  homes[key];
    i = i + 1;
}