【发布时间】:2019-07-10 16:35:55
【问题描述】:
我在尝试通过大量对象(定义为“filteredCharacters”)使用 filter() 时遇到此错误,并且仅将那些与“6”的 id 匹配的对象渲染到屏幕上(只有一个对象)。
我 console.log(filteredCharacters),我可以在控制台中清楚地看到它有效。但由于某种原因,我收到了“Objects are not valid as a React child”错误。
下面的代码来自 /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接受一个返回布尔值的谓词来决定如果为真则保留哪些元素,如果为假则跳过 -
filteredCharacters数组的成员是对象,在渲染这些对象时会出现此错误
标签: javascript arrays reactjs object