【问题标题】:get images from json url using axios使用 axios 从 json url 获取图像
【发布时间】:2021-04-12 06:21:05
【问题描述】:

我是 React 的初学者,试图从 https://api.randomuser.me 获取图像 我正在使用 axios 创建对 api 的获取请求并在 img-wrapper div 中显示图像,但图像没有被导入。我能够获取字符串数据。当我尝试在 img src 中使用 map 时,我收到错误“预期分配或函数调用,而是看到一个表达式”

reactjs

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=>{
                this.setState({ persons: res.data.results });
                
            })
    }

render(){
 
        return (
            <div>
                <section className="login">
                    <div className="loginContainer">
                        <div className="heading">
                        </div>
                        <div className="img-wrapper">
                          
                            <img src={this.state.persons.map(person=>{person.picture.large})}/>
                          
                        </div>

json

{
  "results": [
    {
      "picture": {
        "large": "https://randomuser.me/api/portraits/men/79.jpg",
        "medium": "https://randomuser.me/api/portraits/med/men/79.jpg",
        "thumbnail": "https://randomuser.me/api/portraits/thumb/men/79.jpg"
      },
      "nat": "FI"
    }
  ],
  "info": {
    "seed": "0019bcd5bce99412",
    "results": 1,
    "page": 1,
    "version": "1.3"
  }
}

【问题讨论】:

    标签: javascript json reactjs axios


    【解决方案1】:

    使用Array.map() 迭代this.state.persons 并渲染imgs。

    {this.state.persons.map(person => 
      <img src={person.picture.large}/>
    )}
    

    【讨论】:

      猜你喜欢
      • 2018-10-21
      • 1970-01-01
      • 1970-01-01
      • 2019-12-23
      • 2012-09-16
      • 2016-11-15
      • 2017-02-02
      • 1970-01-01
      • 2019-03-24
      相关资源
      最近更新 更多