简体   繁体   English

无法通过 React 中的查询进行 map

[英]Can't map over a query in React

Im using Apollo with React to map over a query but get a TypeError: Cannot read property 'map' of undefined.我在查询中使用 Apollo 与 map 反应,但得到一个 TypeError: Cannot read property 'map' of undefined。

I don't know if the passing of props is the problem or the query it self...我不知道道具的传递是问题还是它自己的查询......

I know that the Query is in made of fragments but changing that dose not fix the error.我知道查询是由片段组成的,但改变它并不能解决错误。

Here is the code:这是代码:

App.js应用程序.js

import React from 'react';
import './App.css';

import { Query } from 'react-apollo'
import { gql } from  'apollo-boost'

import ListPosts from './components/ListPosts'

function App() {
  return (
    <Query query={GET_POSTS_QUERY}>
      {(data, loading, error) => {
        if (loading) return <div>loading</div>
        if (error) return <div>error</div>

        return <ListPosts posts={data.allPosts} />

      }}
    </Query>
  )
}

const GET_POSTS_QUERY = gql`
{
  allPosts {
    ... on PostType {
      title
      createdAt
      content
      postImage
      postedBy {
        username
      }
    }
    ... on Post2Type {
      title
      createdAt
      content
      postImage
      postedBy {
        username
      }
    }
  }
}

`

export default App;

ListPosts.js ListPosts.js

import React from "react";

const ListPosts = ({ posts }) => (
    <div>
        {posts.map(post => (
            <div key={post.id}>
                <h1>{post.title}</h1>
            </div>
        ))}
    </div>
)

export default ListPosts;

For more context here is the response in JSON有关更多上下文,这里是 JSON 中的响应

{
  "data": {
    "allPosts": [
      {
        "title": "vesti",
        "createdAt": "2020-04-05T12:37:09.451520+00:00",
        "content": "<p><strong>asdasda</strong></p>",
        "postImage": "post/logo.png",
        "postedBy": {
          "username": "filip"
        }
      },
      {
        "title": "asds",
        "createdAt": "2020-04-05T17:44:11.291829+00:00",
        "content": "<p>asdasd</p>",
        "postImage": "",
        "postedBy": {
          "username": "filip"
        }
      }
    ]

Thank you!谢谢!

Query Render prop function Query 渲染道具 function

The render prop function that you pass to the children prop of Query is called with an object ( QueryResult ) that has the following properties.传递给Querychildren属性的渲染属性 function 使用具有以下属性的 object ( QueryResult ) 调用。 This object contains your query result, plus some helpful functions for refetching, dynamic polling, and pagination.这个 object 包含您的查询结果,以及一些用于重新获取、动态轮询和分页的有用功能。

In other words, the render prop is a props object with the properties you need.换句话说,渲染道具是具有您需要的属性的道具 object。 The component is also only passed a single argument.该组件也只传递了一个参数。

The entire props was being assigned to a variable named data , and because loading and error are undefined, ie falsey, those conditional tests fail and you try to render the posts.整个props被分配给一个名为data的变量,并且由于未定义loadingerror ,即错误,这些条件测试失败并且您尝试呈现帖子。 Now, data.allPosts or really props.allPosts doesn't exist.现在, data.allPosts或真正props.allPosts不存在。

Using object destructuring you can access the data , loading , and error props.使用 object 解构,您可以访问dataloadingerror道具。

function App() {
  return (
    <Query query={GET_POSTS_QUERY}>
      {({ data, loading, error }) => {
        if (loading) return <div>loading</div>
        if (error) return <div>error</div>

        return <ListPosts posts={data.allPosts} />

      }}
    </Query>
  )
}

1. your response in JSON isn't the full JSON should be this: 1.您在 JSON 中的回复不是完整的 JSON 应该是这样的:

{
  data: {
    allPosts: [
      {
        title: "vesti",
        createdAt: "2020-04-05T12:37:09.451520+00:00",
        content: "<p><strong>asdasda</strong></p>",
        postImage: "post/logo.png",
        postedBy: {
          username: "filip"
        }
      },
      {
        title: "asds",
        createdAt: "2020-04-05T17:44:11.291829+00:00",
        content: "<p>asdasd</p>",
        postImage: "",
        postedBy: {
          username: "filip"
        }
      }
    ]
  }
}

2. You are sending your data.allpost which shouldn't be camel case so when you receive it as a prop in ListPost you shouldn't wrap it in an object should be: 2.您发送的 data.allpost 不应该是驼峰式的,所以当您在 ListPost 中收到它作为道具时,您不应该将它包装在 object 中应该是:

const ListPosts = (posts) => (...)

3. If you want to map the object you will have to access the array within the object by Object.entries() or Object.values() so: 3. If you want to map the object you will have to access the array within the object by Object.entries() or Object.values() so:

Object.entries(posts).map(postArray => (...)

will return [posts:, [array(2)]]将返回 [posts:, [array(2)]]

4. Now that you have access to the array you will need to map it like you have: 4. 现在您可以访问阵列,您需要像您一样访问 map:

 postArray[1].map(post => {
 return(
  <div key={post.title}>
          <div style={{ borderStyle: "solid" }}>
            <h3>{post.title}</h3>
          </div>
          <div style={{ borderStyle: "solid", borderWidth: "2px" }}>
            <p>{post.createdAt}</p>
            <p>{post.content}</p>
            <p>{post.postImage}</p>
            <p>{post.postedBy.username}</p>
          </div>
  </div>
  )}

I've created an example of this for you for better understanding here: https://codesandbox.io/s/component-drilling-props-grxm4我在这里创建了一个示例供您更好地理解: https://codesandbox.io/s/component-drilling-props-grxm4

Check the console you will be able to see the logs检查控制台,您将能够看到日志

hope this helps you goodluck!希望这可以帮助你好运!

 import React from "react"; const ListPosts = props => { return ( <div> { props.posts.map(post => { <div key={post.id}> <h1>{post.title}</h1> </div> }); } </div> ); }; export default ListPosts;
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

import React from "react";

const ListPosts = props => (
<div>
    {props.posts.map(post => (
        <div key={post.id}>
            <h1>{post.title}</h1>
        </div>
    ))}
</div>
)

export default ListPosts;

can you do these changes?你能做这些改变吗?

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

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