【问题标题】:Next.js commerce / React - useRouter in functional Component - dynamic header localeNext.js commerce / React - 功能组件中的 useRouter - 动态标头语言环境
【发布时间】:2021-08-07 18:53:42
【问题描述】:

我正在研究 Next.JS 商务框架。

为了接收正确的翻译,我必须在我的 graphql API 请求中设置一个动态 Accept-Language 标头。 路由和一切运行良好,当我手动将标题设置为 es = spanish / en-US = english 时,我得到了正确的翻译。

这是我的代码:

import type { GraphQLFetcher } from '@commerce/api'
import fetch from './fetch'
import { API_URL, API_TOKEN } from '../../const'
import { getError } from '../../utils/handle-fetch-response'
import { useRouter } from 'next/router'

const fetchGraphqlApi: GraphQLFetcher = async (
  query: string,
  { variables } = {},
  fetchOptions
) => {
  
  const { locale } = useRouter()
  console.log(locale)

  const res = await fetch(API_URL, {
    ...fetchOptions,
    method: 'POST',
    headers: {
      'Accept-Language': 'es',
      'X-Shopify-Storefront-Access-Token': API_TOKEN!,
      ...fetchOptions?.headers,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      query,
      variables,
    }),
  })

  const { data, errors, status } = await res.json()

  if (errors) {
    throw getError(errors, status)
  }
  return { data, res }
}
export default fetchGraphqlApi

我想使用我可以在所有组件中执行的 next/router 检索语言环境。 当我尝试在上面发布的代码中执行此操作时,我收到以下错误:

服务器错误 错误:无效的挂钩调用。 Hooks 只能在函数组件的主体内部调用。

我很困惑。这不是功能组件吗? 为什么我不能调用任何钩子?

有什么想法可以让它工作吗?

感谢您的帮助。

【问题讨论】:

    标签: reactjs react-hooks next.js shopify commerce


    【解决方案1】:

    根据React.js docs

    (This) 函数是一个有效的 React 组件,因为它接受一个带有数据的“props”(代表属性)对象参数并返回一个 React 元素。

    你的函数接受多个参数,并返回一个对象而不是一个有效的 React 元素。这就是钩子无法将您的函数识别为功能组件的原因。

    【讨论】:

      猜你喜欢
      • 2015-10-20
      • 1970-01-01
      • 2021-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多