You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中使用array.map时,如何仅获取数组中的2个对象?

实现仅渲染数组前2个对象的几种方法

嘿,这个需求很容易搞定,我给你分享两种常用的实现方案:

方案一:使用Array.slice()(推荐)

slice()方法可以安全截取数组的指定片段(不会修改原数组),我们只需要在map遍历前,截取数组的前2个元素即可。修改render方法里的代码就行:

修改后的完整组件代码:

class App extends React.Component {
  constructor() {
    super();
    this.state = {items: []}
  }
  componentWillMount() {
    fetch('https://swapi.co/api/people/?format=json')
      .then(response => response.json())
      .then(({results: items}) => this.setState({items}))
  }
  render() {
    let items = this.state.items
    return (
      <div>
        <ul>
          {/* 用slice(0,2)截取数组前2个元素 */}
          {items.slice(0, 2).map((item) => <li key={item.url}> {item.name} </li> )}
        </ul>
      </div>
    )
  }
}
ReactDOM.render( <App />, document.getElementById('container'))

小提示:原代码里的item.id在SWAPI的返回数据中并不存在,我改成了item.url作为列表项的key(因为url是唯一标识),你也可以替换成其他合适的唯一字段。

方案二:通过索引判断过滤

在map遍历的时候结合索引判断,只渲染索引小于2的元素:

{items.map((item, index) => {
  // 仅渲染前2个元素
  if (index < 2) {
    return <li key={item.url}> {item.name} </li>
  }
  return null
})}

这种方法也能实现需求,但相比slice()会遍历数组所有元素,所以如果数组规模较大,slice()的性能表现会更优。

内容的提问来源于stack exchange,提问作者amitpowerpeace

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:59:51