![](/img/trans.png)
[英]Error: Objects are not valid as a React child when trying to map a nested array for a table component in React
[英]Objects are not valid as a React child when trying to map
我正在嘗試從我的 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;
奇怪的是,當我從渲染中刪除 getUserLikes() 函數時,映射似乎有效,但是當我添加它時,它卻沒有。
問題是getUserLikes
是async
。
當以async
調用函數時,它將返回一個 Promise 對象,該對象不是可渲染的。
如果你想在render
內部調用一些函數,它不能是async
。
即使getUserLikes
不調用異步請求,如果在它前面添加async
,它也會返回一個promise
對象。
您可以在下面的示例中看到這種行為。
async function call1() { return 1; } function call2() { return 1; } // Promise Object console.log(call1()) // Actual returned value console.log(call2())
如果你想獲取數據並渲染它,你應該在componentDidMount
獲取它,而不是在渲染中。
問題在於處理程序的async
性質。 組件返回的語句必須是純的。 您不能在jsx
塊中聲明命令式代碼。
通常在這種情況下,您希望聲明一個本地狀態,該狀態最終會填充返回的數據並在此之前充當占位符。
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.