簡體   English   中英

你如何在無頭 wordpress 中使用 nextjs [id].js 進行服務器端渲染? 使用 graphql 從 Wordpress 獲取單個頁面。比如 service/[id].js

[英]How do you do server side rendering with nextjs [id].js in headless wordpress? fetch single page using graphql from Wordpress. like service/[id].js

我有一個使用 apollo graphql 從后端獲取數據的 nextjs 項目。 我正在嘗試使用服務器端渲染來渲染我的頁面。 但我目前正在使用 graphql apollo hooks 從后端獲取我的數據,而 react hooks 阻止我在 getServerSideProps 中調用我的后端。
使用來自 Wordpress 的 graphql 使用干凈的 URL(如services/[id].js)創建和獲取單個頁面注意:警告顯示(錯誤:響應不成功:收到狀態代碼 500)

 import {
    gql,
    ApolloClient,
    InMemoryCache
  } from "@apollo/client";

  export const client = new ApolloClient({
    uri: 'https://.........../graphql',
    cache: new InMemoryCache()
  });

const serviceDetail = (serviceOutput) => {
    return (
            <div>
                {serviceOutput.serviceTitle}
                {serviceOutput.serviceContent}
            </div>
    )
}

export const getServerSideProps = async (context) => {
    const result = await client.query({
        query: gql` 
              query serData($id: id!) {
                HomePage: pageBy(uri: "https://......./home/") {
                aboutSection {
                    serviceSec(id: $id) {
                        id
                        serviceTitle
                        serviceContent
                        serviceImage {
                            sourceUrl
                        }
                    }
                }
                }
              }
            `,
        variables: {
          id: context.params.id
      }
    })

    return {
        props: {
            serviceOutput: result.data.HomePage.aboutSection.serviceSec;
        },
    };
}

export default serviceDetail;

我不是專家,但據我所知。 您不能將 Apollo 與 next.js 獲取方法(ssg、ssr、isr)一起使用。

Apollo 在客戶端運行查詢,可以與 useQuery 和 useLazyQuery 一起使用。 而 next.js 的抓取則完全不同。

我將在這里演示 2 種方法。

-- 使用阿波羅 --

const FETCH_ALL = gql`
  query MyQuery($first: Int!, $after: String) {
    posts(first: $first, after: $after) {
      edges {
        node {
          title
        }
      }
    }
  }
`;

export default function LoadMoreList() {
  const { data } = useQuery(FETCH_ALL, {
    variables: { first: 5, after: null },
    notifyOnNetworkStatusChange: true,
  });
return (
    <>
      <div>
        {postdata.map((node, index) => {
          {
            return (
              <div key={index}>
                <h1>{node?.node?.title}</h1>
              </div>
            );
          }
        })}
      </div>
     </>
)}

=== 使用 fetch 和 getStaticProps ==

--File1(這是一個 fetch function,您將查詢和變量傳遞給它)

async function fetchAPI(query, { variables } = {}) {
  const headers = { "Content-Type": "application/json" };

  const res = await fetch(process.env.WP_API, {
    method: "POST",
    headers,
    body: JSON.stringify({ query, variables }),
  });

  const json = await res.json();
  if (json.errors) {
    console.log(json.errors);
    throw new Error("Failed to fetch API");
  }

  return json.data;
}
export default fetchAPI;

-- File2(這是包含您的查詢的文件)

import fetchAPI from "./fetching";

export async function homeheadposts() {
  const data = await fetchAPI(
    `
      query homeheadposts {
        posts(first: 7) {
            edges {
                node {
                    id
                    slug
                    title
                    featuredImage {
                        node {
                            sourceUrl
                         }
                    }
                    excerpt(format: RAW)
                }
            }
        }
    }
`
  );

  return data?.posts;

}

-- File3(放置這個 function,你想調用和使用數據的地方,)

    export async function getStaticProps() {
      const latestPosts = await homeheadposts();
      return {
        props: { latestPosts },
      };
    }
export default function CallingData({ latestPosts }) {
  console.log(latestPosts);
  return <h1>hello</h1>;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM