简体   繁体   English

尝试映射时,对象作为 React 子对象无效

[英]Objects are not valid as a React child when trying to map

I'm trying to fetch data from my api and render it as a list but it keeps giving me the error mentionned in the title.我正在尝试从我的 api 获取数据并将其呈现为列表,但它一直给我标题中提到的错误。

import React, { Component } from "react";
import "./style/list.css";
import { getEvents } from "../services/eventService";
import { thisExpression } from "@babel/types";

class Likes extends Component {
  constructor(props) {
    super(props);
    this.state = {
      events: []
    };
  }
  async componentWillMount() {
    const { data: events } = await getEvents();
    this.setState({ events });
    console.log(events);
  }

  async getUserLikes() {
    // Get Likes TODO
    return 1;
  }

  render() {
    return (
      <div>
        <ul class="list-group">
          {this.state.events.map(event => (
            <li
              class="list-group-item d-flex justify-content-between align-items-center"
              key={event._id}
            >
              {event.title}
              <span class="badge badge-primary badge-pill">
                {this.getUserLikes()}
              </span>
            </li>
          ))}
        </ul>
      </div>
    );
  }
}

export default Likes;

Weirdly enough though , it seems when i remove the getUserLikes() function from the render the mapping works but when i add it, it doesn't.奇怪的是,当我从渲染中删除 getUserLikes() 函数时,映射似乎有效,但是当我添加它时,它却没有。

The problem is that getUserLikes is async .问题是getUserLikesasync

When calling a function as async , it will return a Promise object, which isn't a renderable.当以async调用函数时,它将返回一个 Promise 对象,该对象不是可渲染的。

If you want to call some function inside render , it can't be async .如果你想在render内部调用一些函数,它不能是async

Even if getUserLikes doesn't call an async request, if you add async in front of it, it will return a promise object.即使getUserLikes不调用异步请求,如果在它前面添加async ,它也会返回一个promise对象。

You can see this behavior in the example bellow.您可以在下面的示例中看到这种行为。

 async function call1() { return 1; } function call2() { return 1; } // Promise Object console.log(call1()) // Actual returned value console.log(call2())

If you want to fetch data and render it, you should fetch it in componentDidMount , not inside render.如果你想获取数据并渲染它,你应该在componentDidMount获取它,而不是在渲染中。

The problem is the async nature of your handler.问题在于处理程序的async性质。 The returned statement of a component must be pure.组件返回的语句必须是纯的。 You can't declare imperative code inside a jsx block.您不能在jsx块中声明命令式代码。

Usually in cases like that you want to declare a local state which eventually gets filled with the returned data and acts like a placeholder until then.通常在这种情况下,您希望声明一个本地状态,该状态最终会填充返回的数据并在此之前充当占位符。

const Component = () =>{
    const [data, setData] = useState(null)

    useEffect(() =>{
        fetch(/*..*/).then(response => setData(response))
    },[])

    return data ? data.map(/*...*/) : <div> Loading </div>
}

暂无
暂无

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

相关问题 错误:尝试 map 为 React 中的表组件的嵌套数组时,对象作为 React 子项无效 - Error: Objects are not valid as a React child when trying to map a nested array for a table component in React 尝试在render()中返回Node时,“对象作为React子无效” - “Objects are not valid as a React child” when trying to return a Node inside render() 尝试响应 MAP 数据时出现错误。 对象作为 React 子对象无效(找到:object 和键 {children}),我该如何解决? - I AM HAVING ERROR WHEN TRYING TO MAP A DATA IN REACT . Objects are not valid as a React child (found: object with keys {children}), How do i solve it? ReactJS &amp; Javascript: Getting “Error: Objects are not valid as a React child” when trying to set JSON Objects into a state hook - ReactJS & Javascript: Getting “Error: Objects are not valid as a React child” when trying to set JSON Objects into a state hook 使用 Map 函数编写 React 组件时,对象不能作为 React Child 有效 - Objects are Not Valid as React Child when using Map Function to write React Components 尝试基于 AsyncStorage React-Native 渲染组件时,对象作为反应子对象无效 - objects are not valid as a react child when trying to render component based off of AsyncStorage React-Native 反应 | 尝试推送到 state 数组时出现错误“对象作为 React 子项无效” - React | error "Objects are not valid as a React child" when trying to push to state array React Map返回的对象错误作为React子元素无效 - react map returned error of Objects are not valid as a React child “对象作为 React 子项无效” - “Objects are not valid as a React child” “对象作为 React 子对象无效” - 'Objects are not valid as a React child'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM