React + Gatsby静态查询+ GraphQL中的条件渲染

时间:2020-07-02 01:42:39

标签: javascript reactjs graphql gatsby

我想从graphql中选择特色帖子(3个帖子),然后在我的博客页面中显示,所以我只将查询限制为三个结果,但是如果我只有一个帖子,则该网站将失败。

因为我正在使用staticquery来获取数据,在这种情况下,我应该在staticquery组件中使用 render 属性,并且不能在属性上以及在graphql时使用if块不会找到其他会失败的帖子。

代码在这里:

featured-posts.js

import React from "react"
import MiniFeatured from "../components/minifeatured"
import { StaticQuery, Link, graphql } from "gatsby"

const Featured = () => {
    return (
        <StaticQuery
            query={graphql`
                query FeaturedBlogsport {
                    allMarkdownRemark (
                        limit: 3
                        sort: {order: DESC, fields: [frontmatter___date]}
                        filter: {frontmatter: {featured: {eq: true}}}
                    ) {
                        edges {
                            node {
                                frontmatter {
                                    title
                                    description
                                    post_image
                                }
                                fields {
                                    slug
                                }
                            }
                        }
                    }
                }               
            `}
            render={data => (
                <div className="mainBlogposts">
                    <div 
                        className="featuredBlogpost"
                        style={{backgroundImage: `url('${data.allMarkdownRemark.edges[0].node.frontmatter.post_image}')`}}    
                    >
                        <div className="featuredBlogpostContent">
                            <Link to={`https://strokequote.co/${data.allMarkdownRemark.edges[0].node.fields.slug}`}>
                                <h1 className="featuredBlogpostTitle">
                                    {data.allMarkdownRemark.edges[0].node.frontmatter.title}
                                </h1>
                                <h6 className="featuredBlogpostAuthor">
                                    {data.allMarkdownRemark.edges[0].node.frontmatter.description}
                                </h6>
                            </Link>
                        </div>
                    </div>
                    <div className="minifeaturedBlogpostsContainer">
                        <MiniFeatured
                            title={data.allMarkdownRemark.edges[1].node.frontmatter.title}
                            description={data.allMarkdownRemark.edges[1].node.frontmatter.description}
                            postImage={data.allMarkdownRemark.edges[1].node.frontmatter.post_image}
                            slug={data.allMarkdownRemark.edges[1].node.fields.slug}
                        />

                        <MiniFeatured
                            title={data.allMarkdownRemark.edges[2].node.frontmatter.title}
                            description={data.allMarkdownRemark.edges[2].node.frontmatter.description}
                            postImage={data.allMarkdownRemark.edges[2].node.frontmatter.post_image}
                            slug={data.allMarkdownRemark.edges[2].node.fields.slug}
                        />
                    </div>
                </div>
            )}
        />
    )
}

export default Featured

PDD。缩微版是其他组件中的次要贴子。 PDD 2。对不起,我的英语,我还在学习

2 个答案:

答案 0 :(得分:1)

我相信找到解决办法。使用gatsby的def pygirl(test_list): indices = [i for i, v in enumerate(test_list) if v =='x'] return [test_list[i:j] for i, j in zip([0]+indices, indices+[None])][1:] class get_indices(object): def __init__(self, value): self.value = value self.i = 0 def __call__(self, value): # For masking self.i += (value == self.value) return self.i def pygirl2(test_list): return [list(g) for _, g in groupby(test_list, key=get_indices('x'))] def trenton(test_list): result = list() chunk = list() delimiter = 'x' len_test_list = len(test_list) for i, v in enumerate(test_list, 1): if (v == delimiter) & (i != 1): result.append(chunk) chunk = [v] if i == len_test_list: result.append(chunk) elif (i == len_test_list): chunk.append(v) result.append(chunk) else: chunk.append(v) return result def trenton2(test_list): dd = defaultdict(list) # defaultdict delim = 'x' counter = 0 for v in test_list: if v == delim: counter += 1 dd[counter].append(v) else: dd[counter].append(v) return list(dd.values()) def trenton3(test_list): dd = dict() # regular dict delim = 'x' counter = 0 for v in test_list: if v == delim: counter += 1 if dd.get(counter) == None: dd[counter] = [v] else: dd[counter].append(v) return list(dd.values()) def mrnobody33(test_list): variable = "x" st=''.join(list(map(str,test_list))) regex=f'({variable}[^{variable}]*)' return [[k if not k.isdigit() else int(k) for k in v] for v in re.findall(regex,st)] def rakesh(test_list): variable = "x" output = [] for k, v in groupby(test_list, lambda x: x==variable): v = list(v) if k: for i in v: output.append([i]) else: output[-1].extend(v) return output def ansfourtytwo(test_list): variable = 'x' idx = [ix for ix, val in enumerate(test_list) if val==variable] return [test_list[i:j] for i,j in zip(idx, idx[1:]+[len(test_list)])] def sahasrara62(test_list): variable = "x" sol = [] tmp = [] for char in test_list: if char==variable and tmp: sol.append(tmp) tmp = [char] else: tmp.append(char) if tmp: sol.append(tmp) return sol def prashant(test_list): delim = 'x' finalList = [] chunk = [] for val in test_list: if val == delim: finalList.append(chunk) chunk = [delim] else: chunk.append(val) finalList.append(chunk) return finalList[1:] def kevin(test_list): var = "x" r = [] left, right = 0, 0 while left < len(test_list)-1: left = right if test_list[left] == var: right += 1 if right < len(test_list)-1: while test_list[right] != "x": right += 1 else: right = len(test_list) r.append(test_list[left:right]) left += 1 return r ,我可以执行以下操作:

useStaticQuery

答案 1 :(得分:0)

为什么要使用StaticQuery来实现这一目标?您只需使用常规的GraphQL查询即可完成此操作,例如:

import { graphql, Link } from 'gatsby';
import React from 'react';

const Featured = ({ data }) => {
  return <div>
    {data.allMarkdownRemark.edges.map(({ node: post }) => {
      return <div className="mainBlogposts">
        <div className="featuredBlogpost"
             style={{ backgroundImage: `url(${post.frontmatter.post_image})` }}>
          <div className="featuredBlogpostContent">
            <Link to={`https://strokequote.co/${post.fields.slug}`}>
              <h1 className="featuredBlogpostTitle">
                {post.frontmatter.title}
              </h1>
              <h6 className="featuredBlogpostAuthor">
                {post.frontmatter.description}
              </h6>
            </Link>
          </div>
        </div>
      </div>;
    })}
  </div>;
};

export const AboutMeData = graphql`    
    query FeaturedBlogsport {
        allMarkdownRemark (
            limit: 3
            sort: {order: DESC, fields: [frontmatter___date]}
            filter: {frontmatter: {featured: {eq: true}}}
        ) {
            edges {
                node {
                    frontmatter {
                        title
                        description
                        post_image
                    }
                    fields {
                        slug
                    }
                }
            }
        }
    }
`;

我所做的只是使用HTML结构简单地获取所有3篇文章并循环浏览它们。我在node的iterable变量中使用了结构化,将post别名为{ node: post },但理想情况下,所有这些HTML都应该是另一个孤立的组件(它确实很大),并且您应该传递post作为对他们的prop,但目前可以使用。

上面的代码段将简单地打印查询可以获取的帖子数量,无论是1、2还是3。

此外,它比手动访问每个数组位置([0][1]等)还干净。