【问题标题】:Print all elements of fetched data array in react在反应中打印获取的数据数组的所有元素
【发布时间】:2021-01-23 09:33:41
【问题描述】:

嘿,我是 react 的初学者,尝试制作我的第一个全栈应用程序,我正在使用 axios 从 mongodb 获取数据并将数据存储在 fetchedjobs 数组中。 Jobtitle 数组仅具有 fetchedjobs 的 title 属性,我想打印所有条目但无法打印。现在,我通过对索引 {this.state.jobtitle[0]} 进行硬编码来打印这些元素。 请帮忙


class FindJob extends Component{
    constructor(props){
        super(props);
        this.state={
            fetchedjobs:[],
            jobtitle:[],
        }

    }

    componentDidMount(){
        axios.get(' http://localhost:4002/api/findjob')
            .then(res=>{
                this.setState({
                    fetchedjobs:res.data
                })
                let jobtitle=[]
                this.state.fetchedjobs.map(fetchedjob=>
                    jobtitle.push(fetchedjob.jobtitle)
                )
                console.log(jobtitle[0])
                this.setState({
                    jobtitle
                })
            
            })
    }
    render(){
        return(
            <div className="content">
                <h5>{this.state.jobtitle[0]}</h5>
            </div>
        );
    }
}
export default FindJob;

获取的json

[
    {
        "_id": "600469700459a40c088f3dde",
        "jobtitle": "swe",
        "company": "ibm",
        "officelocation": "ggn",
        "jobtype": "Part Time",
        "publisher": "sid",
        "date": "2021-01-17T16:44:32.084Z",
        "__v": 0
    },
    {
        "_id": "600469aa0459a40c088f3ddf",
        "jobtitle": "janitor",
        "company": "cisco",
        "officelocation": "delhi",
        "jobtype": "Full Time",
        "publisher": "tanmya",
        "date": "2021-01-17T16:45:30.218Z",
        "__v": 0
    },
    {
        "_id": "60046ae8b95ae81c14278f9e",
        "jobtitle": "fljdk",
        "company": "ndkf",
        "officelocation": "mdfkfm",
        "jobtype": "Part Time",
        "publisher": "tanmya",
        "date": "2021-01-17T16:50:48.311Z",
        "__v": 0
    }
]

【问题讨论】:

标签: json reactjs mongodb axios


【解决方案1】:

您可以在 setState 方法中创建同步调用并尝试一下,

axios.get(' http://localhost:4002/api/findjob')
    .then(res=>{
        this.setState({ fetchedjobs:res.data }, () => {
            let jobtitle=[]
            this.state.fetchedjobs.map(fetchedjob=>
                jobtitle.push(fetchedjob.jobtitle)
            )
            this.setState({ jobtitle})
        })
    })

【讨论】:

    【解决方案2】:

    试试这个:

    render(){
            return(
                <div className="content">
                   {this.state.jobtitle.length?this.state.jobtitle.map((item)=>{
                    return <h5>{item._id}</h5>    //here you can display any property that you wish to
                    })
        :null}
                </div>
            );
        }
    

    【讨论】:

      猜你喜欢
      • 2021-06-06
      • 2021-10-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-06
      • 2021-04-07
      • 2017-08-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多