【问题标题】:Why it is giving me 'this.state.UserData.map' is not a function?为什么它给我 'this.state.UserData.map' 不是一个函数?
【发布时间】:2019-05-29 05:53:18
【问题描述】:

我的代码中出现错误“this.state.UserData.map”不是函数。我想使用 fetch 从数据库中获取列表。我想我忘记了什么。 请帮我删除这个错误。提前致谢。 这是我显示列表的完整代码...

import React from 'react';
import ReactDOM from 'react-dom';
export default class FetchedData extends React.Component{
  constructor(props){
    super(props);
    this.state={ UserData:[] };
    this.headers=[
      {key:1,label:'Name'},
      {key:2,label:'Department'},
      {key:3,label:'Marks'},
    ];
  }

  componentDidMount(){
    fetch("https://www.veomit.com/test/zend/api/fetch.php")
    .then(response => {
                return response.json();
            })
    .then(result => {
                this.setState({
                    UserData:result
                })
        .catch(error => {
        console.log(
          "An error occurred while trying to fetch data from Foursquare: " +error
        );
      });
    });
  }
  render(){
    return(
      <div>
      <table className="table table-bordered">
          <thead>
            <tr>
              {
                        this.headers.map(function(h) {
                            return (
                                <th key = {h.key}>{h.label}</th>
                            );
                        })
                        }
            </tr>
          </thead>
          <tbody>
              {
                        this.state.UserData.map(function(item){             
                        return (
                                <tr>
                                  <td>{item.name}</td>
                                  <td>{item.department}</td>
                                  <td>{item.marks}</td>
                                </tr>
                            );
                        })
                    }
          </tbody>
      </table>
      </div>
    );
  }
}
````````

【问题讨论】:

  • .then(result =&gt; {...}) 中,执行console.log(result)。这是什么?
  • 表示this.state.UserData不是数组。查看URL,它是一个对象。
  • 你能告诉我console.log(result)是什么吗?可能的原因是您的结果不是Array
  • 是的,你是对的,它不是一个数组。我在控制台中获取对象。
  • 你的代码给了我'Cannot read property 'name' of null'错误。

标签: javascript arrays reactjs object ecmascript-6


【解决方案1】:

请替换您的代码,希望它对您有用。

谢谢

 import React from 'react';
    import ReactDOM from 'react-dom';
    export default class FetchedData extends React.Component{
      constructor(props){
        super(props);
        this.state={ UserData:[] };
        this.headers=[
          {key:1,label:'Name'},
          {key:2,label:'Department'},
          {key:3,label:'Marks'},
        ];
      }

       componentWillMount() {
            fetch("https://www.veomit.com/test/zend/api/fetch.php")
            .then(response => {
                 return response.json();
            })
            .then(result => {
                this.setState({
                    UserData: result
                });
             })
             .catch(function(error) {
                    console.log(
                    "An error occurred while trying to fetch data from Foursquare: " +
                          error
                    );
            });
        }
      render(){
        return(
          <div>
          <table className="table table-bordered">
              <thead>
                <tr>
                  {
                            this.headers.map(function(h) {
                                return (
                                    <th key = {h.key}>{h.label}</th>
                                );
                            })
                            }
                </tr>
              </thead>
              <tbody>
                  { this.state.UserData.length > 0 ?
                         this.state.UserData.map((item,index) => (
                             <tr key={index}>
                                      <td>{item.name}</td>
                                      <td>{item.department}</td>
                                      <td>{item.marks}</td>
                                    </tr>
                          ))
                          ) : (
                               <tr>
                                  <td colspan="3">No record found.</td>
                                </tr>
                              )}
                  </tbody>
          </table>
          </div>
        );
      }
    }
    ````````

【讨论】:

  • 他给 this.state.UserData.length > 0 ?
  • @JackBashford 请检查您的 .map 函数。你还需要检查你的数据长度。
  • 但它是一个对象,而不是一个数组 - 请参阅我的答案。对象没有length
  • 在这个语句中 .then(result => { this.setState({ UserData:result }) 你的结果应该返回一个对象数组,因为你将 UserData 声明为一个数组。如果 this.state。 UserData 不是一个数组,那么你如何映射它。
  • @SanatGupta 你能检查和编辑这个 this.state.UserData.map((item,index) => ( {item.name} {item.department} {item.marks} )): ( 没有找到记录。 )}
【解决方案2】:

数据是一个对象——你需要用Object.values把它转换成一个数组:

UserData: Object.values(result)

【讨论】:

  • 现在它给了我 'Cannot read property 'name' of null error'
【解决方案3】:

响应不是数组。您需要将响应服务器转换为对象数组才能使用地图

响应必须是这样的。你可以告诉后端服务像这样改变,或者像这样转换到你的状态

[{name: 'John Doe', department: 'CEO', marks: 'title' } , {....} ]

【讨论】:

    猜你喜欢
    • 2021-05-29
    • 1970-01-01
    • 2021-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-25
    • 1970-01-01
    • 2020-03-08
    相关资源
    最近更新 更多