【问题标题】:Component is returning a TypeError: Cannot read property 'map' of undefined组件返回 TypeError:无法读取未定义的属性“地图”
【发布时间】:2019-09-17 19:29:03
【问题描述】:

我在运行我的应用程序时收到以下错误消息。

TypeError: Cannot read property 'map' of undefined

我将 Grid.js 导入到我的 Index.js 文件中,如下所示。我希望 Grid.js 显示在 Index.js 页面上,但是我收到 TypeError: Cannot read property 'map' of undefined error。

Grid.js

import React, { Component } from 'react';
import axios from 'axios';

class Grid extends React.Component {
  state = {
    posts: [],
    isLoading: true,
    errors: null
  };

  getPosts() {
    axios
      .get("http://localhost:1337/posts")
      .then(response => {
        this.setState({
          posts: response.data.posts,
          isLoading: false
        });
      })
      .catch(error => this.setState({ error, isLoading: false }));
  }

  componentDidMount() {
    this.getPosts();
  }
    render(){
      const { isLoading, posts } = this.state;
      return <div>
        <div className="row">

          {!isLoading ? (
            posts.map(post => {
              const { _id, title, content } = post;
              return (


    <div className="col-lg-2 col-md-3 col-sm-6 col-6" key={_id}>
        <div className="list-item slick-item r list-hover mb-3">
          <div className="media text-hover-primary">
            <span className=" media-content"><i className="fas fa-images fa-4x text-muted"></i></span> 
            <div className="media-action media-action-overlay">
              <div className="row">

                <div className="w-100 text-center mt-2 h-1x">
                Misc Meta Properties
                </div>

                <div className="w-100 text-center mt-4">
                  <a className="btn btn-sm btn-outline-light btn-rounded mx-3" href="{item.url}">View Type</a>
                </div>
              </div>
            </div>
          </div>
          <div className="list-content text-center">
            <div className="list-body">
                      <a className="list-title title" href="{item.url}">{title}</a>
                      <a className="list-subtitle d-block text-muted subtitle text-small ajax" href="{item.url}">Brand</a> 
            </div>
          </div>
        </div>
</div>  );
            })
          ) : (
            <p>

            </p>

          )}

            </div></div>

    }
  }
export default Grid; 

Index.js(页面/index.js)

import Header from '../components/Header'
import Grid from '../components/Grid'
import Welcome from '../components/Welcome'
import Footer from '../components/Footer'
import "../style.css"

const Index = () => (
  <div>
    <body className="bg-dark">
    <Header></Header>
    <Welcome></Welcome>
    <div className="container">
        <Grid/>
        <Footer/>
    </div>
    </body>
  </div>
)

export default Index

使用 NextJs 的 getInitialProps 函数时,我能够成功读取和显示数据。但是,我希望这个 API 放在一个我可以调用的漂亮组件文件中,而不是把它全部放在 Index.js 页面上,然后用 this.props.title 等对其进行迭代。

有什么想法吗?

编辑:

从控制台: [{"id":1,"title":"test","content":"test","created_at":1556521391304,"updated_at":1556521391312},{"id":2,"title":"test ","content":"test","created_at":1556521394698,"updated_at":1556521394702}]

直接从 API (Strapi) 浏览到 http://localhost:1337/posts/ 时 [{"id":1,"title":"test","content":"test","created_at":1556521391304,"updated_at":1556521391312},{"id":2,"title":"test ","content":"test","created_at":1556521394698,"updated_at":1556521394702}]

【问题讨论】:

  • 你能记录response.data.posts的值吗?
  • 确保您在 response.data.posts 中获取值数组
  • 是的,它显示在 console.log 中
  • 试试条件posts &amp;&amp; posts.map
  • @MattCohen,你能在你的帖子中发布日志值吗?

标签: reactjs next.js


【解决方案1】:

我假设您使用的是 nextjs。这意味着初始化页面加载来自服务器而不是客户端。在 nextjs 中有一个方法调用getinitialprops,它获取任何数据并创建道具。

【讨论】:

    【解决方案2】:

    更新 !isLoading ? (posts.map( 代码如下:

    !isLoading && posts && Array.isArray(posts) ? posts.map(...) : ""
    

    【讨论】:

      【解决方案3】:

      在你使用posts.map的render()方法中,第一次检查render方法时发生了什么反应,第一次post是一个空数组,所以在你的render方法中使用下面的代码。

      render(){
            var { posts } = this.state;
            var displayContent = !posts?[]:posts.map((data,index) => {
                                  return {data.title}
                                  })
      

      在此使用主要返回方法编写您的 HTML 代码之后,只需在您希望它的简单方法处使用 {displayContent} 即可......

      您指定的上述错误发生是因为 post[] 第一次是空的..所以使用上面的代码它可以工作...

      当您有空时,请通过以下链接 React Lifecycle Methods。

      Life Cycle Methods

      【讨论】:

      • 感谢您的建议,不幸的是仍然无法正常工作。
      • 能不能把截图上传一下,方便我查一下。
      【解决方案4】:

      在使用 map 函数之前,请确保您的数据应该返回数组,并且它在 map 函数级别喊不为空检查,如

      render(){
        const { isLoading, posts } = this.state;
        return <div>
          <div className="row">
      
            {!isLoading ? (
              posts !=null&&posts.length>0&&posts.map(post => {
                const { _id, title, content } = post;
                return (
      
      
      <div className="col-lg-2 col-md-3 col-sm-6 col-6" key={_id}>
          <div className="list-item slick-item r list-hover mb-3">
            <div className="media text-hover-primary">
              <span className=" media-content"><i className="fas fa-images fa-4x text-muted"></i></span> 
              <div className="media-action media-action-overlay">
                <div className="row">
      
                  <div className="w-100 text-center mt-2 h-1x">
                  Misc Meta Properties
                  </div>
      
                  <div className="w-100 text-center mt-4">
                    <a className="btn btn-sm btn-outline-light btn-rounded mx-3" href="{item.url}">View Type</a>
                  </div>
                </div>
              </div>
            </div>
            <div className="list-content text-center">
              <div className="list-body">
                        <a className="list-title title" href="{item.url}">{title}</a>
                        <a className="list-subtitle d-block text-muted subtitle text-small ajax" href="{item.url}">Brand</a> 
              </div>
            </div>
          </div>
      

      ); }) ) : (

              </p>
      
            )}
      
              </div></div>
      
      }
      

      【讨论】:

        【解决方案5】:

        您没有从服务器响应中获得posts,或者您对该响应的处理不当。

        如果您不想在服务器出现故障时出现“错误”,您可以从 {!isLoading ? ( 切换到 {(post &amp;&amp; post.length) ? (

        【讨论】:

          猜你喜欢
          • 2022-01-14
          • 2019-03-02
          • 1970-01-01
          • 1970-01-01
          • 2021-08-17
          • 2021-11-17
          • 2022-01-12
          • 2021-02-23
          相关资源
          最近更新 更多