【问题标题】:TypeError: this.state.data.map in reactjs类型错误:reactjs 中的 this.state.data.map
【发布时间】:2021-11-22 01:39:36
【问题描述】:
class Home extends Component {
  constructor(props) {
    super(props);
    this.state = {
      data: [],
      isLoaded: false,
    };
  }

  componentDidMount() {
    fetch("https://reqres.in/api/users?page=2")
      .then((res) => res.json())
      .then((json) => {
        this.setState({
          isLoaded: true,
          data: json,
 
        });
      });
  }

  render() {

var { isLoaded, data }= this.state;

if(!isLoaded){
  return<div>Is isLoaded</div>
}

else{

    return (
      <div>
        <ul>
          {() =>
            this.state.data.map((data, index) => (
              <li key={index}>Email: {data.email}</li>
            ))
          }
          ;
        </ul>
        
      </div>
    );
  }
}
}

export default Home;

大家好,我知道这个问题被问了很多次,但我无法弄清楚我得到了错误。我已经检查了与此类似的所有问题,但如果我使用另一个链接,即“https://jsonplaceholder.typicode.com/users”,则没有找到具体的解决方案,这个代码工作正常。

【问题讨论】:

标签: javascript reactjs react-native api axios


【解决方案1】:

从https://reqres.in/api/users?page=2 返回的数据不是一个数组,而是一个具有data 属性的对象,其中包含您要查找的内容(一个数组)。请求的结果是:

{"page":1,"per_page":6,"total":12,"total_pages":2,"data":[{"id":1,"email":"george.bluth@reqres.in","first_name":"George","last_name":"Bluth","avatar":"https://reqres.in/img/faces/1-image.jpg"},{"id":2,"email":"janet.weaver@reqres.in","first_name":"Janet","last_name":"Weaver","avatar":"https://reqres.in/img/faces/2-image.jpg"},{"id":3,"email":"emma.wong@reqres.in","first_name":"Emma","last_name":"Wong","avatar":"https://reqres.in/img/faces/3-image.jpg"},{"id":4,"email":"eve.holt@reqres.in","first_name":"Eve","last_name":"Holt","avatar":"https://reqres.in/img/faces/4-image.jpg"},{"id":5,"email":"charles.morris@reqres.in","first_name":"Charles","last_name":"Morris","avatar":"https://reqres.in/img/faces/5-image.jpg"},{"id":6,"email":"tracey.ramos@reqres.in","first_name":"Tracey","last_name":"Ramos","avatar":"https://reqres.in/img/faces/6-image.jpg"}],"support":{"url":"https://reqres.in/#support-heading","text":"To keep ReqRes free, contributions towards server costs are appreciated!"}}

因此,您不能对请求的结果使用来自Array prototype 的map 函数。您必须先访问 data 属性:

this.state.data.data.map((data, index) => ( // note the double data
  <li key={index}>Email: {data.email}</li>
))

您还可以将json.data 分配给state.data 以避免丑陋的.data.data:

this.setState({
  isLoaded: true,
  data: json.data, // note the .data
});

【讨论】:

    【解决方案2】:

    我认为问题在于您的 .map() 方法的括号中。请试试这个

    class Home extends Component {
      constructor(props) {
        super(props);
        this.state = {
          data: [],
          isLoaded: false,
        };
      }
    
      componentDidMount() {
        fetch("https://reqres.in/api/users?page=2")
          .then(res => res.json())
          .then(json => {
            this.setState({
              isLoaded: true,
              data: json,
            });
          });
      }
    
      render() {
        const { isLoaded, data } = this.state;
    
        if (!isLoaded) {
          return <div>Is isLoaded</div>;
        } else {
          return (
            <div>
              <ul>
                {data?.map((data, index) => {
                  return <li key={index}>Email: {data.email}</li>;
                })}
              </ul>
            </div>
          );
        }
      }
    }
    
    export default Home;
    

    【讨论】:

    • 不,它也不起作用。
    【解决方案3】:

    我没有看到任何错误,一切正常。

    输出:

    工作示例:StackBlitz

    import * as React from 'react';
    import { Text, View, StyleSheet } from 'react-native';
    import Constants from 'expo-constants';
    class App extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          data: [],
          isLoaded: false,
        };
      }
    
      componentDidMount() {
        fetch('https://reqres.in/api/users?page=2')
          .then((res) => res.json())
          .then((json) => {
            console.log(json.data);
            this.setState({
              isLoaded: true,
              data: json.data,
              email: null,
            });
          });
      }
    
      render() {
        var { isLoaded, data } = this.state;
    
        if (!isLoaded) {
          return <div>Is isLoaded</div>;
        } else {
          return (
            <div>
              <div className="contents home">
                <img
                  src="https://trucard.io/india/wp-content/uploads/2021/08/2021-June-TruCard-Logo.png
    "
                  width={50}
                  alt="img"
                  className="trucard-img"
                />
              </div>
              <div className="button">
                <button className="button-button">Load list</button>
              </div>
              <ul>
                {this.state.data?.map((data, index) => (
                  <li key={index}>Email: {data.email}</li>
                ))}
                ;
              </ul>
            </div>
          );
        }
      }
    }
    
    export default App;
    
    

    【讨论】:

    • 当您运行代码时,它不会在控制台上出现任何错误,但在浏览器中会显示“TypeError: data.map is not a function Home.render E:/Project/Login/trucard/src /Components/Home.js:51 48 |
      49 | 50 |
      > 51 |
        | ^ 52 | {data.map((data, index) => { 53 | return
      • Email: {data.email}
      • ; 54 | })} 查看编译“如下。
    • 您修改了初始代码,通过在获取时将 json.data(而不是整个 json)分配给 state.data,从而解决了 OP 的问题
    • @Gaurav,我刚刚检查了控制台输出,没有错误。这是示例:stackblitz.com/edit/react-tmveqp
    猜你喜欢
    • 2018-08-06
    • 2019-04-29
    • 1970-01-01
    • 2021-02-19
    • 2021-10-23
    • 1970-01-01
    • 1970-01-01
    • 2016-10-04
    • 2020-08-06
    相关资源
    最近更新 更多