简体   繁体   中英

reactjs-jsx count index in map()

I'm coding and I got stuck with some issue with JSX.

How can I count index in the .map() method?

I need to get only the first 5 title in my code, I use the axios module to get the data from an database, and I need to get only the first 5 titles in my state.

import React, {Component} from "react"
import UserUtils from "./UserUtils"
class Ex6_2Comp extends Component
{
    constructor()
    {
        super()
        this.state = {userid : "" , user : {} ,titles : []}
    }
    getData =  async () =>
    {
        let resp = await UserUtils.getUserFullData(`http://jsonplaceholder.typicode.com/users/${this.state.userid}`);
        await this.setState({user : resp.data})
        let resp_todo = await UserUtils.getUserFullTodos()
        let AllTitle = resp_todo.filter(x => x.userId == this.state.userid)
        let userTitle = AllTitle.map(x =>x.title)
        this.setState({titles : userTitle})
        

        
    }
    render()
    {
        
        let items = this.state.titles.map((item,index) => 
                {
                    
                    return <li key={index}>{item}</li>
                })
       
       
        return(
            <div className="App">
             Id:   <input type="text" onChange={e => this.setState({userid : e.target.value})}></input>
            <br/>
            <input type="button" value="getData" onClick={this.getData}/>
            <br/>
            Name : {this.state.user.name}
            <br/>
            email : {this.state.user.email}
            <br/>
            <ul>
                {items}
            </ul>
            </div>
        )
    }
}
export default Ex6_2Comp

You can use .slice() as the following:

let items = this.state.titles.slice(0, 5)
                             .map((item,index) => <li key={index}>{item}</li>)

Read from the documentation of .slice() :

The slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included) where start and end represent the index of items in that array. The original array will not be modified.

See a working example with .slice(0, 5) as:

 const titles = [{id:1},{id:2},{id:3},{id:4},{id:5},{id:6},{id:7}] const result = titles.slice(0, 5) console.log({result})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM