首页 > 解决方案 > 反应错误 - 无法读取未定义的属性“状态”

问题描述

我正在关注使用 fetch 的本教程;我能够使用这个模拟 API 提取照片:https ://randomuser.me/api/ ...但是修改了代码以从 API 中提取其他数据,例如名字。但是,在这个过程中遇到了一个错误:

这是代码:

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';

class App extends Component {

  constructor(){
    super();
    this.state = {
      pictures: [],
      people: [],
    };
  }

  componentWillMount()
  {
    fetch('https://randomuser.me/api/?results=10')
    .then(results => results.json())
    .then(data => this.setState({ pictures: data.results }))
    .then(data => this.setState({ people: data.results }));
  }



    render()  {
      console.log(this.state);
      return (
        <div>
            {
              this.state.pictures.map( pic =>(<div><img src={pic.picture.medium} /></div>) ).
              this.state.people.map(person => (<div>{person.name.first}</div>))
            }    
        </div>
      );
    }
  }

export default App;

基本上,我试图弄清楚如何提取更多图片(来自 API 的其他数据),并且不确定我是否走在正确的轨道上。目前,我正在尝试获取名字。请问我能得到一些帮助吗?

标签: javascriptreactjsapicomponents

解决方案


每个表达式都应该用 括起来{}

{this.state.pictures.map(pic => (
  <div>
    <img src={pic.picture.medium} />
  </div>
))}
{this.state.people.map(person => <div>{person.name.first}</div>)}

推荐阅读