nextjs 中的头脚本 application/ld+json 触发 ESLint:无法读取未定义的 属性 '0'

Head script application/ld+json in nextjs triggers ESLint: Cannot read property '0' of undefined

我有一些类似的代码。我需要添加 application/ld+json 结构化数据,但这样做会触发此 ESLint 错误:

ESLint: Cannot read property '0' of undefined 它指的是 scriptStringProduct 道具。即使我只在该变量未定义的情况下生成该代码,我也会收到此错误。 如何解决?

import Head from 'next/head';
import { IHeadTags } from '../../../utils/types';

export const Index: React.FC<IHeadTags> = (props: IHeadTags) => {
    scriptStringProduct = { __html: '' },
    isProduct = false
  } = props;

  return (
    <Head>
      {isProduct && scriptStringProduct !== undefined && (
        <script
          type='application/ld+json'
          dangerouslySetInnerHTML={scriptStringProduct ?? { __html: '' }}
          key='scriptStringProduct-jsonld'
        />
      )}
    </Head>
  );
};

export default Index;

在您的 .eslintrc.json 文件中,您需要关闭 next-script-for-ga 的规则。

示例:

// .eslintrc.json

{
  "settings": {
    "react": {
      "version": "detect"
    }
  },
  "env": {
    "browser": true,
    "es2021": true,
    "node": true
  },
  "extends": [
    "eslint:recommended",
    "next",
    "plugin:react/recommended",
    "plugin:@typescript-eslint/recommended"
  ],
  "parser": "@typescript-eslint/parser",
  "parserOptions": {
    "ecmaFeatures": {
      "jsx": true
    },
    "ecmaVersion": 12,
    "sourceType": "module"
  },
  "plugins": ["react", "@typescript-eslint"],
  "rules": {
    "react/prop-types": "off",
    "react/react-in-jsx-scope": "off",
    "@typescript-eslint/no-explicit-any": "off",
    "@next/next/no-document-import-in-page": "off",
    "@next/next/next-script-for-ga": "off" // make sure to have this rule off
  }
}