简体   繁体   English

Javascript data.map 不是函数

[英]Javascript data.map is not a function

Hey i've been working on a full stack app with Vue.Js, NodeJS, ExpressJS and mongoDB and i have a PostService.js class in my frontend that handles my http requests.嘿,我一直在使用 Vue.Js、NodeJS、ExpressJS 和 mongoDB 开发一个完整的堆栈应用程序,我的前端有一个 PostService.js 类来处理我的 http 请求。 In this class i'm mapping the response that i'm getting from my api but the problem is that when i try to map the response i'm getting and error.在这个课程中,我正在映射从我的 api 获得的响应,但问题是当我尝试映射响应时,我得到了错误。

The error says data.map is not a function错误说 data.map 不是函数


So what's the solution so i can map my data and show it in front-end?那么解决方案是什么,以便我可以映射我的数据并在前端显示它?

错误

PostService.js: PostService.js:


const url = "http://localhost:9000/api/posts/";

class PostService {
  static getPosts() {
    return new Promise(async (resolve, reject) => {
      try {
        const res = await axios.get(url);
        const data = res.data;
        resolve(
          data.map(post => ({
            ...post,
            createdAt: new Date(post.createdAt)
          }))
        );
      } catch (err) {
        reject(err);
      }
    });
  }
}

PostComponent.vue : PostComponent.vue :

  <div class="container">
    <h1>Latest posts</h1>
    <hr />
    <p class="error" v-if="error">{{ error }}</p>
    <div class="posts-container">
      <div
        class="post"
        v-for="(post, index) in posts"
        v-bind:item="post"
        v-bind:index="index"
        v-bind:key="post._id"
      >
        {{`${post.createdAt.getDate()}/${post.createdAt.getMonth()}/${post.createdAt.getFullYear()}`}}
        <p class="text">{{ post.text }}</p>
      </div>
    </div>
  </div>
</template>

<script>
import PostService from "../PostService";

export default {
  name: "PostComponent",
  data() {
    return {
      posts: [],
      error: "",
      text: ""
    };
  },
  async created() {
    try {
      this.posts = await PostService.getPosts();
    } catch (err) {
      this.error = err.message;
    }
  }
};
</script>

<style scoped>
...just styling in here
</style>

So can anyone help me why am i getting that error任何人都可以帮助我为什么我会收到那个错误

From your question, I'm assuming your res value from await axios.get(url) looks like this:根据您的问题,我假设您从await axios.get(url) res值如下所示:

{
     posts: [],
     error: "",
     text: ""
}

If thats the case, it is an object , not an array.如果是这样,它是一个object ,而不是一个数组。 Map is an array builtin function ( array.map ) Map 是一个数组内置函数( array.map

What you want to map is the posts array in the response您要映射的是响应中的posts数组

data.posts.map(post => ({
            ...post,
            createdAt: new Date(post.createdAt)
          }))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM