不能在reactjs的return语句中使用filter函数.引发错误



我正试图直接在return语句下过滤数据。我得到了这个错误";对象作为React子对象无效。如果您想要呈现子集合,请改用数组";。地图功能运行良好。映射和过滤两个返回阵列

这是我的代码

export class TestPage extends Component {
constructor(){
super();
this.state = {
proPlayerData: []
}
}
componentDidMount(){
this.fetchData();
this.filterData();
}
filterData = () => {
}
fetchData = async() => {
const playerData = await fetch("https://api.opendota.com/api/playersByRank");
const player_data = await playerData.json()
console.log("fetch",player_data);
await this.setState({proPlayerData: [...player_data]})
}
render() {
// let topTenIds = this.state.proPlayerData
// console.log(topTenIds)
return (
<div>
{this.state.proPlayerData.filter((data,index) => {
if(index <= 10){
return <div key={index}>data.accountId</div>
}
})}
</div>
)
}

}

导出默认的TestPage

为什么我不能像地图一样使用过滤器?

Array.prototype.map数据从一种格式转换为另一种格式,它在中将您的数据数组转换为JSX时非常有用

Array.prototype.filter将过滤数据数组中的数据,但不会更改格式,因此,如果您从一个对象数组开始,您将以相同形状的对象数组结束(如果没有满足回调条件,则为空数组(

您需要两者的组合,首先是filter来过滤您想要的数据,然后是map来将过滤后的数据转换为JSX,但即使不是过滤器,它会迭代每个元素,您也只需要前10个,看看您的示例,因此您可以使用Array.prototype.slice-

this.state.proPlayerData
.slice(0, 10)
.map((data) => (<div key={index}>{data.accountId}</div>))

编辑。。。看起来你可能想要前11个,因此更新切片参数以适应。。。

最新更新