【问题标题】:Map function with Graphql, React使用 Graphql、React 映射函数
【发布时间】:2019-07-23 09:52:29
【问题描述】:

我正在使用 Gatsby(React 和 Graphql)编写一个小型博客应用程序。有个小东西我不太明白。这是我的博客页面代码:

const Blog = ({ data }) => {
  console.log(data)
  return (
  <Layout>
    <h1>Blog</h1>
    {data.allMarkdownRemark.edges.map(({ node }) => (
      <div key={node.id}>
        <h3>{node.frontmatter.title}</h3>
      </div>
    ))}
  </Layout>)
}

export default props => (
<StaticQuery
      query={graphql`
        query {
  allMarkdownRemark {
    totalCount
    edges {
      node {
        id
        frontmatter {
          title
          path
          date
          tags
        }
      }
    }
  }
}
      `}
      render={ data => <Blog data={data} {...props} />} 
    />
)

让我感到困惑的是这一行:

{data.allMarkdownRemark.edges.map(({ node }) => (

我的问题是,为什么这会返回错误:

{data.allMarkdownRemark.edges.map( node  => (

为什么需要大括号?混淆来自于我们已经从 markdownremark.edges 接收列表的事实,那么为什么我们必须再次指定它是动态生成的内容呢?这是一个graphql的东西吗?

很高兴知道答案,在此先感谢。

【问题讨论】:

    标签: reactjs graphql gatsby


    【解决方案1】:

    这是 Javascript 解构功能...

     let test = [{name : 'sathish'},{name : 'steve'}];
    
     //here you are access directly with destructuring es6 feture
     test.map(({name})=>{console.log(name)}
    
     test.map((fullObj)=>{console.log(fullObj.name)})
    

    Refere this -> js destructuring...

    【讨论】:

      【解决方案2】:

      这是对象解构和属性简写功能。
      1.) What will happen when using curly braces..
      -> 当您在边列表上使用 map 进行迭代时,您会在 map 函数中获得边对象,同时您明确提到要从边对象中破坏节点属性。

       {data.allMarkdownRemark.edges.map(({ node }) => (
            <div key={node.id}>
              <h3>{node.frontmatter.title}</h3>
            </div>
          ))}
      

      2.) What will happen when curly braces not use.
      -> 当您遍历边列表上的地图时,您将获得边对象作为函数内的参数。在这种情况下,您必须显式访问节点属性。

       {data.allMarkdownRemark.edges.map( edge  => (
            <div key={edge.node.id}>
              <h3>{edge.node.frontmatter.title}</h3>
            </div>
          ))}
      

      参考:Destructing Feature 希望它可以消除您的疑问..

      【讨论】:

      • 谢谢!对于其他回复,非常感谢您的帮助:)
      【解决方案3】:

      如果我理解得很好,那么您不知道为什么节点周围需要花括号。 这是一种称为解构的 es6 语法。当函数参数具有属性时,您可以通过这种方式提取该属性。

      ({ node }) => ( <div key={node.id}> // you can use the node here 
      

      等价于。

      (data) => ( <div key={data.node.id}>  // you must use the property thought the parameter
      

      您可以在此处阅读更多信息:http://es6-features.org/#ObjectMatchingShorthandNotation

      【讨论】:

        猜你喜欢
        • 2017-07-18
        • 2020-08-29
        • 2022-12-31
        • 1970-01-01
        • 2018-09-10
        • 2017-07-02
        • 1970-01-01
        • 2021-03-18
        • 1970-01-01
        相关资源
        最近更新 更多