gpt4 book ai didi

javascript - 如何修复 'Objects are not valid as a React child'

转载 作者:行者123 更新时间:2023-11-30 19:48:24 25 4
gpt4 key购买 nike

Codesandbox link .

我在尝试通过大量对象(定义为“filteredCharacters”)使用 filter() 时遇到此错误,并且仅将那些与 id 为“6”匹配的对象呈现到屏幕(只有一个对象)。

我使用 console.log(filteredCharacters),我可以在控制台中清楚地看到它有效。但出于某种原因,我收到了“对象作为 React 子项无效”的错误抛出。

下面的代码来自/components/content.js,在上面的 Codesandbox 链接中。

import React, { Component } from 'react';
import Intro from '../intro/intro';

class Content extends Component {
render() {
// Grab the 'characters' object from App.js, and assign it to 'this.props'
const { characters } = this.props;

// Filter the chracters and return only whose 'id' belongs to that of '6'
const filteredCharacters = characters.filter(characters => {
if (characters.id === 6) {
return (
<div className="characters" key={characters.id}>
<p>Name: {characters.Name}</p>
<p>ID: {characters.id}</p>
<p>Job: {characters.Job}</p>
<p>Age: {characters.Age}</p>
<p>Weapon: {characters.Weapon}</p>
<p>Height: {characters.Height}</p>
<p>Birthdate: {characters.Birthdate}</p>
<p>Birthplace: {characters.Birthplace}</p>
<p>Bloodtype: {characters.Bloodtype}</p>
<p>Description: {characters.Description}</p>
</div>
)
}
});

// Check to see if it logs properly (it does)
console.log(filteredCharacters);

// When trying to render this to the screen below, it doesn't work

return (
<div>
{filteredCharacters}
</div>
)
}
}

export default Content;

最佳答案

filter 只会创建一个新数组,其中包含从函数返回真值的所有元素。

您可以先使用 filter 获取相关字符,然后在新数组上使用 map 获取您要渲染的 JSX。

const filteredCharacters = characters
.filter(character => character.id === 6)
.map(character => (
<div className="characters" key={character.id}>
<p>Name: {character.Name}</p>
<p>ID: {character.id}</p>
<p>Job: {character.Job}</p>
<p>Age: {character.Age}</p>
<p>Weapon: {character.Weapon}</p>
<p>Height: {character.Height}</p>
<p>Birthdate: {character.Birthdate}</p>
<p>Birthplace: {character.Birthplace}</p>
<p>Bloodtype: {character.Bloodtype}</p>
<p>Description: {character.Description}</p>
</div>
));

关于javascript - 如何修复 'Objects are not valid as a React child',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54727872/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com