簡體   English   中英

在 React JSON 返回:意外的令牌,預期的“,”

[英]in React JSON Return : Unexpected token, expected “,”

我的 React 返回出現語法錯誤

語法錯誤:意外的標記,應為“,”

如果我刪除

{data.nodes && data.nodes.map((node) => (
              {node.title}
              ))}

我收到一個不同的錯誤,但我確實在終端中看到了所有 JSON 數據,所以我知道它正在被拉取。 我在返回時無法循環/映射它

如果我刪除 map... 錯誤:對象作為 React 子項無效(找到:[object Promise])。 如果您打算渲染一組子項,請改用數組。

所以我的邏輯是將數據呈現為 JSX,然后將其從 GetSlides 傳遞到 Page。 您也會看到 {page} 也通過了,但效果很好

async function GetSlides() {

const data = await getHomeSlides()
console.log(data)

 if (!data) return null;    
    
  return (
    
      <div>
        <h1>Slides</h1>

         {data.nodes && data.nodes.map((node) => (
          {node.title}
          ))}
      
     </div>
  )
    
}

export default function Page( {page} ) {


  return (
    <>
      <Layout>
        <Head>
          <title>{ page.seo.title }</title>
          <meta name="description" content={page.seo.metaDesc} />
        </Head>
       <Header />
        <ContainerFull>
          <h1>{ page.title }</h1>
            <GetSlides />
          <div dangerouslySetInnerHTML={{ __html: page.content }} />

          
        </ContainerFull>
      </Layout>
    </>
  )
}

這是查詢

const API_URL = process.env.WORDPRESS_API_URL

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

  if (process.env.WORDPRESS_AUTH_REFRESH_TOKEN) {
    headers[
      'Authorization'
    ] = `Bearer ${process.env.WORDPRESS_AUTH_REFRESH_TOKEN}`
  }

  const res = await fetch(API_URL, {
    method: 'POST',
    headers,
    body: JSON.stringify({
      query,
      variables,
    }),
  })

  const json = await res.json()
  if (json.errors) {
    console.error(json.errors)
    throw new Error('Failed to fetch API')
  }
  return json.data
}

export async function getHomeSlides() {
  const data = await fetchAPI(`
         {
          artwork {
            nodes {
              artwork {
                available
                description
                medium
                price
                size
                arttypedisplay
                homePageSlideshow
              }
              title
              uri
              slug
              seo {
                metaDesc
                title
              }
            }
          }
        }

  `)
  return data?.artwork
}

您試圖使您的GetSlides組件async React 不是這樣工作的,渲染 function 是 100% 同步的,應該沒有副作用。 useEffect掛鈎中獲取數據並將結果存儲在本地組件 state 中。 異步 function效果回調中聲明,因為反應掛鈎也是同步的。

function GetSlides() {
  const [data, setData] = React.useState({
    nodes: [],
  });

  React.useEffect(() => {
    const fetchHomeSlides = async () => { // <-- create async function
      const data = await getHomeSlides()
      console.log(data);
      setData(data);
    };

    fetchHomeSlides(); // <-- invoke on component mount
  }, []); // <-- empty dependency array to run once on mount

  if (!data.nodes.length) return null; // <-- return null if nodes array empty
    
  return (
    <div>
      <h1>Slides</h1>

      {data.nodes.map((node, index) => (
        <React.Fragment key={index}> // <-- use react key
          {node.title} // <-- render title
        </React.Fragment>
      ))}
    </div>
  )
    
}

感謝 Drew Reese 的深刻見解。

最終代碼涉及將兩個查詢放入 getStaticProps

import Head from 'next/head'
import Link from 'next/link'
import ContainerFull from '../components/container-full'
import MoreStories from '../components/more-stories'
import HeroPost from '../components/hero-post'
import Intro from '../components/intro'
import Layout from '../components/layout'
import { getHomePage, getHomeSlides } from '../lib/api'
import { CMS_NAME } from '../lib/constants'
import Header from '../components/header'


export default function Page( {page, artwork} ) {

    

  return (
    <>
      <Layout>
        <Head>
          <title>{ page.seo.title }</title>
          <meta name="description" content={page.seo.metaDesc} />
        </Head>
       <Header />
        <ContainerFull>
          <h1>{ page.title }</h1>
            
          <div dangerouslySetInnerHTML={{ __html: page.content }} />

        {artwork.nodes && artwork.nodes.map((arts) => (
          <span>{arts.title}</span>
          ))}
      
          
        </ContainerFull>
      </Layout>
    </>
  )
}



export async function getStaticProps({ params }) {
    
    
  const data = await getHomePage()
  console.log(data)
  
   const art = await getHomeSlides()
  console.log(art)
  
  return {
    props: {
      page: data,
      artwork: art,
    },
  }
}

暫無
暫無

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

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