简体   繁体   English

对象作为 React 子项无效。 如果您打算呈现子集合,请改用数组

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

I am setting up a React app with a Rails backend.我正在设置一个带有 Rails 后端的 React 应用程序。 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."我收到错误消息“对象作为 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?我究竟做错了什么?

Your data homes is 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>
  );

I had a similar error while I was creating a custom modal.我在创建自定义模式时遇到了类似的错误。

const CustomModal = (visible, modalText, modalHeader) => {}

Problem was that I forgot that functional components can have only one prop passed to them, according to the REACT documentation:问题是我忘记了功能组件只能传递一个道具,根据 REACT 文档:

This function is a valid React component because it accepts a single “props” (which stands for properties) object argument with data and returns a React element.这个函数是一个有效的 React 组件,因为它接受一个带有数据的“props”(代表属性)对象参数并返回一个 React 元素。 We call such components “function components” because they are literally JavaScript functions.我们称此类组件为“函数组件”,因为它们实际上是 JavaScript 函数。 React docs反应文档

Therefore when we want to pass several variables we need to wrap them into an object or an Array and pass the pointer to that array or object.因此,当我们想要传递几个变量时,我们需要将它们包装到一个对象或数组中,并将指针传递给该数组或对象。 And destructure it on the component side before invoking the component.并在调用组件之前在组件端对其进行解构。 Alternatively we can use curly braces to indicate that we are sending an object with identical property names and variables that contain the value of those properties, like in the example here.或者,我们可以使用花括号来表示我们正在发送一个具有相同属性名称和包含这些属性值的变量的对象,就像这里的示例一样。 And then define the function also to destructure upon arrival of the properties contained in the object.然后定义该函数以在对象中包含的属性到达时进行解构。

const CustomModal = ({visible, modalText, modalHeader}) => {}

If you have multiple values to pass to the component, you should pass an object, thus curly brackets around its properties/variables (assuming they have the same name).如果您有多个值要传递给组件,则应该传递一个对象,因此在其属性/变量周围使用花括号(假设它们具有相同的名称)。

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 render function 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 && 
                this.props.orders.length > 0 && 
                this.props.orders.map(order => (
                <Order 
                    key={order.id}
                    ingredient={order.ingredients}
                    price={order.price} />
                ))
            }
        </div>
    );
    return orderDetails;
}

In above code snippet : If return orderDetails is sent as return {orderDetails} then the error posted in this question pops up despite the value of 'orderDetails' (value as <Spinner/> or null or JSX related to <Order /> component).在上面的代码片段中:如果return orderDetails作为return {orderDetails}发送,那么尽管 'orderDetails' 的值(值作为<Spinner/>null或与<Order />组件相关的 JSX),仍会弹出此问题中发布的错误.

Error description : react-dom.development.js:57 Uncaught Invariant Violation: Objects are not valid as a React child (found: object with keys {orderDetails}).错误描述:react-dom.development.js:57 Uncaught Invariant Violation:对象作为 React 子项无效(发现:带有键 {orderDetails} 的对象)。 If you meant to render a collection of children, use an array instead.如果您打算渲染一组子项,请改用数组。

We cannot return a JavaScript object from a return call inside the render() method.我们不能从 render() 方法中的返回调用返回一个 JavaScript 对象。 The reason being React expects some JSX, false, null, undefined, true 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.原因是 React 期望在 UI 中呈现一些 JSX、false、null、undefined、true 而不是我在使用return {orderDetails}时尝试呈现的一些 JavaScript 对象,因此会出现上述错误。

VALID :有效的 :

<div />

<div></div>

<div>{false}</div>

<div>{null}</div>

<div>{undefined}</div>

<div>{true}</div>

INVALID :无效的 :

<div>{orderDetails}</div> // This is WRONG, orderDetails is an object and NOT a valid return value that React expects.

Edit: I also got this error on my company's test server used by QA's for their testing.编辑:我在我公司的测试服务器上也遇到了这个错误,QA 用于他们的测试。 I pointed my local code to that test server and tested the scenario in which this error was reported by QA team and found NO ERROR in my local machine.我将我的本地代码指向该测试服务器,并测试了 QA 团队报告此错误的场景,并在我的本地计算机中发现 NO ERROR。 I got surprised.我很惊讶。 I re-checked multiple number of times, re-checked the scenario with QA team and I was doing right but still I was not able to replicate the issue.我重新检查了多次,与 QA 团队重新检查了场景,我做得对,但我仍然无法复制问题。 I consulted my fellow devs but still were not able to figure out the root cause.我咨询了我的开发人员,但仍然无法找出根本原因。 So keeping with the information in the error message I started scanning all the code I had deployed in my last deployment commit ( to be more specific last 4-5 commits because I suspected it could be there from last few deployments but was caught in the current deployment), especially all the components I had developed and found that there was a component - inside which there was no specified condition being met so it was returning NOTHING from it.因此,根据错误消息中的信息,我开始扫描我在上次部署提交中部署的所有代码(更具体地说是最后 4-5 次提交,因为我怀疑它可能在最近几次部署中存在,但在当前部署),尤其是我开发的所有组件,发现有一个组件 - 在其中没有满足指定的条件,因此它没有返回任何内容。 So see below sample pseudo code.所以请看下面的示例伪代码。 I hope it helps.我希望它有所帮助。

render () {
return (
    {this.props.condition1 && (
       return some jsx 1
    )}

    {this.props.condition1 && (
       return some jsx 2
    )})
}

If you see in above pseudo code if condition1 and condition2 are not met then this component will render NOTHING from it and ideally a react component must return some JSX, false, null, undefined, true from it.如果您在上面的伪代码中看到如果条件 1 和条件 2 不满足,那么该组件将不会从中呈现任何内容,理想情况下,反应组件必须从中返回一些 JSX、false、null、undefined、true。

I hope it will help someone else.我希望它会帮助别人。

This error seems to occur also when you UNintentionally send a complex object that includes for example Date to React child components.当您无意中发送包含例如 Date to 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 complex Object under the hood).检查您是否传递了类似的东西(在引擎盖下生成复杂的对象)。 Instead you can send that date as string value and do new Date(string_date) in child component.相反,您可以将该日期作为字符串值发送并在子组件中执行 new Date(string_date) 。

the issue is because you are trying to display the whole object instead of the keys inside the object.问题是因为您试图显示整个对象而不是对象内部的键。

For example: Data is例如:数据是

[
    {
        "status": "success",
        "count": 20511
    },
    {
        "status": "failure",
        "count": 1776
    }
]

Now, in the component read like below, this will work.现在,在如下所示的组件中,这将起作用。

import React, { Component } from 'react';


export default class Display extends Component {

    render() {

        const { data } = this.props;

        return (
            <>
           
               {
                   data.map((value,key)=>
                       <div>{value.status}</div>
                       <div>{value.count}</div>
                   )
               }
            </>

        )
    }
}

This error occur to me when send Date object (for example timestamp in firebse) to React child components.将 Date 对象(例如 firebse 中的时间戳)发送到 React 子组件时,我会发生此错误。

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.如果您将其作为子组件参数的值发送,您将发送一个复杂的对象,并且您可能会收到与上述相同的错误。

You must send that date as string value您必须将该日期作为字符串值发送

        <p>{timestamp.toString()}</p>

should work fine like this.应该像这样正常工作。

Although not specific to the answer, this error mostly occurs when you mistakenly using a JavaScript expression inside a JavaScript context using {}虽然不是特定于答案,但此错误主要发生在您使用 {} 在 JavaScript 上下文中错误地使用 JavaScript 表达式时

For example例如

let x=5;

export default function App(){ return( {x} ); };

Correct way to do this would be正确的方法是

let x=5;
export default function App(){ return( x ); };

I had a similar problem, I forgot to add curly brackets { } while accepting the arguments in the component.我有一个类似的问题,我在接受组件中的参数时忘记添加大括号{ }

I had this: const ServiceCard = (color, title, icon, subtitle) => (我有这个: const ServiceCard = (color, title, icon, subtitle) => (

Then I updated it to this: const ServiceCard = ({color, title, icon, subtitle}) => (然后我将其更新为: const ServiceCard = ({color, title, icon, subtitle}) => (

and it worked.它奏效了。

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,否则你会遇到同样的问题

Objects are not valid as a React child对象作为 React 子对象无效

I also got the same error but with different scenario.我也遇到了同样的错误,但情况不同。 I was learning react useReducer hook and implemented a counter with increment, decrement and reset buttons and I was trying to display the count on to the screen but I was the above mentioned error.我正在学习 react useReducer 钩子并实现了一个带有递增、递减和重置按钮的计数器,我试图在屏幕上显示计数,但我是上面提到的错误。

In the code I had declared the count which is returned by useReducer hook as the object and I was directly trying to return it rather than the count property of it在代码中,我将 useReducer 钩子返回的计数声明为对象,我直接尝试返回它而不是它的计数属性

I should actually return count.count and I was returning count only(object itself) not property.我实际上应该返回 count.count 并且我只返回 count (对象本身)而不是属性。

We can stringify object and return the string also.我们可以将对象字符串化并返回字符串。

import React, { useReducer } from "react";

const initialState = {
count:0,
}
const reducer = (state, action) => {
    switch (action.type) {
        case 'increment':
            return {count:state.count + 1}
        case 'decrement':
            return {count:state.count - 1}
        case 'reset':
            return initialState
        default:
            return state
    }
}

function CounterWithReducer(props) {
  const [count, dispatch] = useReducer(reducer, initialState);

  return (
    <>
      <h1>{count}</h1>
      <button onClick={()=>{dispatch({type:'increment'})}}>Increment</button>

      <button onClick={()=>{dispatch({type:"decrement"})}}>Decrement</button>
      <button onClick={()=>{dispatch({type:"reset"})}}>Reset</button>
    </>
  );
}

export default CounterWithReducer;

In the above code在上面的代码中

{count} {数数}

This section (in the return part ) is where I did the mistake instead of count I need to use count.count这部分(在返回部分)是我做错的地方而不是count我需要使用count.count

Summary is that if you trying to show object on to screen you can't either use JSON.stringify() or try to display any property of the object.总结是,如果您尝试在屏幕上显示对象,则不能使用JSON.stringify()或尝试显示对象的任何属性。

I am in early stage of my developer life please pardon me for any spelling mistakes if any.我处于开发人员生活的早期阶段,如果有任何拼写错误,请原谅我。

I also occured the error,and I sloved it by removing the curly braces,hope it will help someone else.我也发生了错误,我通过删除花括号来解决它,希望它对其他人有帮助。

You can see that ,I did not put the con in the curly brace,and the error occured ,when I remove the burly brace , the error disappeared.你可以看到,我没有把 con 放在花括号里,并且发生了错误,当我删除大括号时,错误消失了。

const modal = (props) => {
const { show, onClose } = props;

let con = <div className="modal" onClick={onClose}>
        {props.children}
        </div>;

return show === true ? (
    {con}
) : (
    <div>hello</div>
);

There are an article about the usage of the curly brace.有一篇文章介绍了花括号的用法。 click here 点击这里

In My case, I had a added async at app.js like shown below.就我而言,我在 app.js 中添加了一个异步,如下所示。

const App = async() => {
return(
<Text>Hello world</Text>
)
}

But it was not necessary, when testing something I had added it and it was no longer required.但这不是必需的,在测试某些东西时我已经添加了它并且不再需要它。 After removing it, as shown below, things started working.删除它后,如下所示,事情开始工作了。

 const App =() => {
    return(
    <Text>Hello world</Text>
    )
}

For my case I had对于我的情况,我有

 return (
    <div >
      {updated.map((one) => {
        <div>
          <h2>{one.name}</h2>
        </div>
      })}

    </div>
  );

Then changed to然后改为

 return (
    <div >
      {updated.map((one,index) => {
        return (
          <div key={index}>
          <h2>{one.name}</h2>
          </div>
        )
      })}

    </div>
  );

The issue was that I had no return statement after the map function问题是我在 map 函数之后没有返回语句

In my case, I had就我而言,我有

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

instead of代替

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

Double curly braces.双花括号。

In JavaScript, arrays and collections are different, although they are somewhat similar, but here the react needs an array.在 JavaScript 中,数组和集合是不同的,虽然它们有些相似,但是这里的 react 需要一个数组。 You need to create an array from the collection and apply it.您需要从collection中创建一个array并应用它。

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

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

Well in my case, the data which I wanted to render contained an Object inside that of the array so due to this it was giving error, so for other people out there please check your data also once and if it contains an object, you need to convert it to array to print all of its values or if you need a specific value then use.就我而言,我想要渲染的数据在数组的数据中包含一个对象,因此它给出了错误,所以对于那里的其他人,请检查你的数据一次,如果它包含一个对象,你需要将其转换为数组以打印其所有值,或者如果您需要特定值然后使用。

My data :我的数据:

body: " d fvsdv"
photo: "http://res.cloudinary.com/imvr7/image/upload/v1591563988/hhanfhiyalwnv231oweg.png"
postedby: {_id: "5edbf948cdfafc4e38e74081", name: "vit"}       
//this is the object I am talking about.
title: "c sx "
__v: 0
_id: "5edd56d7e64a9e58acfd499f"
__proto__: Object

To Print only a single value仅打印单个值

<h5>{item.postedby.name}</h5>

Just to add to the other options, I was trying to access a nested object within the main object through the dot method as in: this.state.arrayData.CompleteAdress.Location In this case Location is a nested object inside Complete address which is why i cant simply access it with the dot notation.只是为了添加其他选项,我试图通过 dot 方法访问主对象中的嵌套对象,如下所示: this.state.arrayData.CompleteAdress.Location在这种情况下,位置完整地址中的嵌套对象,这就是为什么我不能简单地用点符号访问它。

  • So if you're facing this same issue, try JSON.parse so that you access the nested object and then manipulate accordingly.因此,如果您遇到同样的问题,请尝试 JSON.parse 以便访问嵌套对象,然后进行相应操作。

I faced same issue but now i am happy to resolve this issue.我遇到了同样的问题,但现在我很高兴解决这个问题。

  1. npm i core-js
  2. put this line into the first line of your index.js file.将此行放入index.js文件的第一行。 import core-js

In your state, home is initialized as an array homes: []在您所在的州,home 被初始化为数组 home homes: []

In your return, there is an attempt to render home (which is an array).在您返回时,尝试渲染 home(这是一个数组)。 <p>Stuff: {homes}</p>

Cannot be done this way --- If you want to render it, you need to render an array into each single item.不能以这种方式完成 --- 如果要渲染它,则需要将一个数组渲染到每个单个项目中。 For example: using map()例如:使用map()

Ex: {home.map(item=>item)}例如: {home.map(item=>item)}

Had the same error but with a different scenario.有同样的错误,但有不同的场景。 I had my state as我的状态为

        this.state = {
        date: new Date()
    }

so when I was asking it in my Class Component I had所以当我在我的类组件中问它时,我有

p>Date = {this.state.date}</p>

Instead of代替

p>Date = {this.state.date.toLocaleDateString()}</p>

I had this issue when I was trying to render an object on a child component that was receiving props.当我尝试在接收道具的子组件上渲染对象时遇到了这个问题。

I fixed this when I realized that my code was trying to render an object and not the object key's value that I was trying to render.当我意识到我的代码试图呈现一个对象而不是我试图呈现的对象键的值时,我修复了这个问题。

I faced this exact error.我遇到了这个确切的错误。 On tracing the root cause of this issue, I found that the FRONTEND code (React) is making a call to API and showing the response on the page by accessing some property of that response!在追踪此问题的根本原因时,我发现 FRONTEND 代码 (React) 正在调用 API 并通过访问该响应的某些属性在页面上显示响应! So in this case, there are two cases所以在这种情况下,有两种情况

  • Either that property does not exists in the response from backend (it'll throw different error) OR后端的响应中不存在该属性(它会引发不同的错误)或
  • The property from the backend response is a complex object (Object inside Object) which our frontend React component is trying to access, but unable to read because React needs either a STRING (by directly accessing the specifc property eg Object.property) Or array.来自后端响应的属性是一个复杂对象(Object inside Object),我们的前端 React 组件试图访问它,但由于 React 需要一个字符串(通过直接访问特定属性,例如 Object.property)或数组,所以无法读取它。 [This Case] [这个案例]

So we received this error because the React was expecting the STRING but got the object (because you passed Object inside object).所以我们收到这个错误是因为 React 期待 STRING 但得到了对象(因为你在对象内部传递了 Object)。

Please check your Backend logic (API) which is sending the response.请检查发送响应的后端逻辑 (API)。

I had a similar problem but mine this worked.我有一个类似的问题,但我的这个工作。 My output我的输出

But the mistake i had done was simple.但我犯的错误很简单。 In my contents wer more than two and i had forgoten to wrap as an array.在我的内容中超过两个,我忘记了包装为一个数组。 I had not put carly braces.我没有戴上carly 牙套。

import React from 'react'
import {Button} from './Button';
import {Link} from 'react-router-dom'
import './HeroSection.css';

function HeroSection({
    lightBg, topLine, lightText, lightTextDesc, headline, description, 
    buttonLabel, img,alt,imgStart}
) {
    return (
        <>
            <div className={lightBg? 'home__hero-section': 'home__hero-section darkBg'}>
                <div className='container'>
                    <div className="row home__hero-row" 
                    style={{display:'flex', flexDirection:imgStart==='start'?' row-reverse':'row'}}
                    >
                    <div className='col'>
                        <div className='home__hero-text-wrapper'>
                            <div className='topline'>{topLine}</div>
                            <h1 className={lightText? 'heading': 'heading dark'}>{headline}</h1>
 <p className={lightTextDesc? 'home__hero-subtitle': 'home__hero-subtitle dark'}> 
 {description}
 <Link to='/sign-up'>
     <Button buttonSize='btn--wide' buttonColor='blue'>
{buttonLabel}
     </Button>
 </Link>
 </p>
                        </div>

                    </div>

                    <div className='col'>
                        <div className='home__hero-img-wrapper'>
                      <img src={img} alt={alt} className='home_hero-img'/>
                        </div>
                    </div>
                    </div>

                </div>

            </div>

        </>
    );
}

export default HeroSection
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

I had this error when using the BigNumber library on a value before setting to UseState:在设置为 UseState 之前对值使用 BigNumber 库时出现此错误:

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

Same error but a different scenario.同样的错误,但不同的场景。 I intended to assign my custom functional component to layoutComponent prop of a 3rd party module.我打算将我的自定义功能组件分配给第 3 方模块的 layoutComponent 道具。

Erroneous code:错误代码:

customLayout = () => {
// function returning a component
}
//usage:
{customLayout}

Fix:使固定:

CustomLayout = () => {
// functional component
}
//usage:
<CustomLayout></CustomLayout>

There is yet another scenerio I captured.我还捕捉到了另一个场景。 I DOM to be rendered was dependent on some checks.我要渲染的 DOM 依赖于一些检查。 So I initialized it with null and on Switch was giving value to it.所以我用 null 初始化它,并且在 Switch 上给它赋值。 And while returning just returned that DOM.并且在返回时只是返回了那个 DOM。

export function test() {
  let DOM = null;
  switch (conditions) {
    case 1: {
      DOM = <div>SOME DIV</div>;
    }
    case 2: {
      DOM = <div>SOME DIV2</div>;
    }
    default: {
      DOM = null;
    }
  }
  return { DOM }; // -----1 Problem was here
}

Resolution to it was just wrap it with <></>解决它只是用 <></> 包裹它

return <>{DOM}</>

I had the same issue.我遇到过同样的问题。 In my case, I have not render the value of the item.就我而言,我没有渲染项目的价值。 My initial code was,我最初的代码是,

        keyExtractor={(item, index) => item.id}
        data={courseGoals} 
        renderItem={itemData => (
          <View style={styles.listitem}> 
              <Text>{itemData.item}</Text> 
          </View>
        )} 
      />

And I simply added '.value' and it worked!我只是添加了“.value”,它就起作用了!

        keyExtractor={(item, index) => item.id}
        data={courseGoals} 
        renderItem={itemData => (
          <View style={styles.listitem}> 
              <Text>{itemData.item.value}</Text> 
          </View>
        )} 
      />

I had the same issue then I realized that I made the dumbest mistake ever.我有同样的问题,然后我意识到我犯了有史以来最愚蠢的错误。 I had made my component asynchronous, I mean I used the async keyword, something like this我已经让我的组件异步了,我的意思是我使用了 async 关键字,就像这样

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

Then after a lot of headaches and prays, I realized my dumb mistake and removed the async.然后经过很多头痛和祈祷,我意识到我的愚蠢错误并删除了异步。

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

I am using faker.js I was expecting company field to be string but it is an array It was :我正在使用faker.js我希望公司字段是字符串,但它是一个数组它是:

<div className='text-gray-400 text-sm'>works at {s.company}</div>

but instead should be但应该是

<div className='text-gray-400 text-sm'>works at {s.company.name}</div>

I think it is not programmers fault, world is unexpected place and it's data could be anything.我认为这不是程序员的错,世界是意想不到的地方,它的数据可能是任何东西。 React should point out exact error. React 应该指出确切的错误。

如果要显示所有对象而不进行迭代,则必须将数据作为字符串值发送,即

  <p>{variableName.toString()}</>

use moment format because that is date... convert to date format... Moment(array_list_item.close_date).format("MM-DD-YYYY")}使用时刻格式,因为那是日期...转换为日期格式... Moment(array_list_item.close_date).format("MM-DD-YYYY")}

Note: React will not display this type of date format in map function注意:React 不会在 map 函数中显示这种日期格式

"created_at": "2018-09-18T16:39:22.184Z", "created_at": "2018-09-18T16:39:22.184Z",

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 对象作为 React 子级无效。 如果您打算渲染一组子项,请改用数组 - 错误 Solidity - React - Objects are not valid as a React child. If you meant to render a collection of children, use an array instead - Error Solidity - React 错误:对象作为 React 子项无效。 如果您打算渲染一组孩子,请改用数组 - Error: Objects are not valid as a React child. If you meant to render a collection of children, use an array instead 未捕获的不变违规:对象无效作为React子代。 如果要渲染子级集合,请改用数组 - Uncaught Invariant Violation: Objects are not valid as a React child. If you meant to render a collection of children, use an array instead 对象作为 React 子对象无效。 如果您打算渲染一组子项,请改用数组 - FlatList - Objects are not valid as a React child. If you meant to render a collection of children, use an array instead - FlatList ReactJS 错误:对象作为 React 子项无效。 如果您打算渲染一组孩子,请改用数组 - ReactJS Error: Objects are not valid as a React child. If you meant to render a collection of children, use an array instead “对象作为 React 子对象是无效的。 如果您打算渲染一组子项,请改用数组。” 错误 - “Objects are not valid as a React child. If you meant to render a collection of children, use an array instead.” error 如何修复错误:对象作为 React 子对象无效。 如果您打算渲染一组孩子,请改用数组 - How to fix error: Objects are not valid as a React child. If you meant to render a collection of children, use an array instead 错误:对象作为 React 子对象无效。 如果您打算渲染一组子项,请改用数组。 从 JSON 获取数据 - Error: Objects are not valid as a React child. If you meant to render a collection of children, use an array instead. Getting data from JSON 无法显示 ReactJS 中的数据。错误:对象作为 React 子项无效。 如果您打算呈现子集合,请改用数组 - Cannot display data in ReactJS. Error: Objects are not valid as a React child. If you meant to render a collection of children, use an array instead 对象作为 React 子级无效(找到:object 和键 {children})。 如果您打算渲染一组孩子,请改用数组 - Objects are not valid as a React child (found: object with keys {children}). If you meant to render a collection of children, use an array instead
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM