【问题标题】:TypeError: this.state.persons.map is not a function while using axios.get in ReactTypeError: this.state.persons.map 在 React 中使用 axios.get 时不是一个函数
【发布时间】:2021-01-06 11:34:25
【问题描述】:

我是 React 的初学者,试图从 https://api.randomuser.me 获取数据。我正在使用状态人员来存储 json 数据并将其显示在 div -> data-wrapper 现在我只想从 json 文件中提取名称并确保状态人员是一个空数组而不是字符串 请帮忙

reactjs 文件

import React, { Component } from 'react'
import './form.css'
import axios from 'axios'


class form extends Component{
    constructor(props){
        super(props);

        this.state={
            answer:'',
            persons:[]
        }
        this.handleChange=this.handleChange.bind(this);
        this.handleSubmit=this.handleSubmit.bind(this);
    }

    componentDidMount(){
        axios.get('https://api.randomuser.me')
            .then(res=>{
                console.log(res);
                this.setState({persons:res.data});
            })
    }

    handleSubmit=(e)=>{
      
    }

    handleChange=(e)=>{
        this.setState({
            answer:e.target.value,
        })
    }
    render(){
 
        return (
            <div>
                <section className="login">
                    <div className="loginContainer">
                        <div className="heading">
                            
                        </div>
                        <div className="data-wrapper">
                          {this.state.persons.map(person=><h2>{person.name}</h2>)}
                            
                        </div>
                
                    </div>
                </section>
            </div>
        )
    }
}
export default form

json

{
  "results": [
    {
      "gender": "female",
      "name": {
        "title": "Miss",
        "first": "Zuzanna",
        "last": "Wessel"
      },
      "location": {
        "street": {
          "number": 4174,
          "name": "Bård Skolemesters vei"
        },
        "city": "Haugo",
        "state": "Oppland",
        "country": "Norway",
        "postcode": "2832",
        "coordinates": {
          "latitude": "48.2641",
          "longitude": "49.1001"
        },
        "timezone": {
          "offset": "+5:00",
          "description": "Ekaterinburg, Islamabad, Karachi, Tashkent"
        }
      }
    }
  ],
  "info": {
    "seed": "bdb282c01c741bda",
    "results": 1,
    "page": 1,
    "version": "1.3"
  }
}

【问题讨论】:

    标签: javascript json reactjs axios


    【解决方案1】:

    您需要从正确的key 访问数据。你需要这样设置:

    this.setState({ persons: res.data.results });
    

    另外,您需要将名称渲染为字符串,目前,您正在渲染将引发错误的对象。

     <h2>{person.name.first}</h2>
    

    【讨论】:

      猜你喜欢
      • 2022-10-22
      • 2022-01-12
      • 2021-07-11
      • 2019-04-01
      • 2020-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多