【问题标题】:in React JSON Return : Unexpected token, expected ","在 React JSON 返回:意外的令牌,预期的“,”
【发布时间】:2021-01-17 05:50:17
【问题描述】:

我的 React 返回出现语法错误

语法错误:意外标记,应为“,”

如果我删除

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

我得到一个不同的错误,但我确实在我的终端中看到了我的所有 JSON 数据,所以我知道它正在被拉取。我在返回时无法循环/映射它

删除地图时的错误... 错误:对象作为 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
}

【问题讨论】:

  • {node.title} 不是有效的 JSX。你想渲染什么?
  • 现在,我正在尝试遍历数据并显示标题,一旦正确显示并且我可以看到结果,我将对其进行更多格式化
  • 如果node.title 是一个字符串,那么只需删除括号({}),它应该是可渲染的。
  • 好的,现在我得到另一个错误错误:对象作为 React 子级无效(找到:[object Promise])。如果您打算渲染一组子项,请改用数组。在 GetSlides 中(在 pages/index.js:26)
  • 在 Page 函数中使用

标签: reactjs next.js


【解决方案1】:

你试图让你的GetSlides 组件async。 React 不是这样工作的,渲染函数是 100% 同步的,应该没有副作用。在useEffect 挂钩中获取数据并将结果存储在本地组件状态中。异步函数在效果回调中声明,因为反应钩子同步。

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>
  )
    
}

【讨论】:

  • 谢谢你..我们都写了类似的 ;D 代码一次..你的代码和我写的都得到一个新的错误 SyntaxError: JSON.parse: unexpected character at line 1 column 1 JSON 数据和我的终端不再显示数据.. 仅供参考,我正在使用 next,js 以防发生任何变化
【解决方案2】:

感谢 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,
    },
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-07
    • 1970-01-01
    • 2018-09-20
    • 1970-01-01
    • 2018-09-13
    • 2021-03-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多