我正在设置一个带有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;

我做错了什么?


当前回答

当我将Date对象(例如firebse中的时间戳)发送到React子组件时,发生了这个错误。

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

您必须将该日期作为字符串值发送

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

应该可以这样工作。

其他回答

对象作为React子对象无效

我也得到了相同的错误,但情况不同。我正在学习react useReducer钩子,并实现了一个带有增量,减量和重置按钮的计数器,我试图在屏幕上显示计数,但我是上述错误。

在代码中,我声明了由useReducer钩子返回的count作为对象,我直接尝试返回它,而不是它的count属性

我应该返回count。我只返回count(对象本身)而不是property。

我们也可以stringify object并返回字符串。

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;

在上面的代码中

{数}

这个部分(在返回部分)是我犯错误的地方,我需要使用count.count而不是count

总结是,如果你试图在屏幕上显示对象,你既不能使用JSON.stringify(),也不能尝试显示对象的任何属性。

我正处于开发生涯的早期阶段,如果有拼写错误,请原谅我。

这个问题是因为您试图显示整个对象,而不是对象内部的键。

例如:数据是

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

现在,在如下所示的组件中,这将工作。

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>
                   )
               }
            </>

        )
    }
}

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

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

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

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

您的数据家是一个数组,因此您必须使用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>
  );

我有一个类似的问题,我忘记在接受组件中的参数时添加花括号{}。

我有这个:const ServiceCard =(颜色,标题,图标,subtitle) => (

然后我将其更新为:const ServiceCard =({颜色,标题,图标,subtitle}) => (

这招奏效了。