gpt4 book ai didi

typescript - useStaticQuery : Invalid hook call. Hooks只能在函数组件体内调用

转载 作者:行者123 更新时间:2023-12-04 15:42:24 30 4
gpt4 key购买 nike

我正在尝试通过 useStaticQuery 从 gatsby-config.js 获取值。我的代码如下。

谁能有解决这个问题的想法?

提前致谢

repo
https://github.com/koji/portfolio

包.json

"dependencies": {
"@babel/core": "^7.5.5",
"gatsby": "^2.13.28",
"gatsby-link": "^2.2.2",
"gatsby-plugin-react-helmet": "^3.1.2",
"gatsby-plugin-sass": "^2.1.3",
"gatsby-plugin-typescript": "^2.1.2",
"gatsby-source-filesystem": "^2.1.8",
"gatsby-source-instagram-all": "^2.0.5",
"gatsby-transformer-remark": "^2.6.10",
"node-sass": "^4.12.0",
"react": "^16.8.6",
"react-dom": "^16.8.6",
"webpack": "^4.36.1"
},
"devDependencies": {
"@types/react": "^16.8.24",
"@types/react-dom": "^16.8.5",
"@types/react-helmet-async": "^1.0.0",
"env-cmd": "^9.0.3",
"eslint-plugin-react-hooks": "^1.6.1",
"gatsby-plugin-tslint": "^0.0.2",
"tslint": "^5.18.0",
"tslint-loader": "^3.5.4",
"tslint-react": "^4.0.0",
"typescript": "^3.5.3"
}

网站元数据.ts

import { useStaticQuery, graphql } from "gatsby";
export const useSiteMetadata = () => {
const { site } = useStaticQuery(
graphql`
query {
site {
siteMetadata {
title
author
}
}
}
`);
return site.siteMetadata.title;
};
import * as React from "react";
import { useSiteMetadata } from 'siteMetadata'


export default class Header extends React.Component {
render() {
const {title} = useSiteMetadata();
return (
<h1>
<Link className={headerStyles.title} to="/">
{title}
</Link>
</h1>
)
}
}

Gatsby -config.js

module.exports = {
siteMetadata: {
title: "page title",
author: "me"
}
}

最佳答案

组件名称首字母未大写导致此问题;

useStaticQuery 不是那样工作的,您需要在您在那里使用它的组件内呈现依赖于此查询的组件的子组件;

组件 UseSiteMetadata 将是:

import { useStaticQuery, graphql } from "gatsby";
export const useSiteMetadata = () => {
const { site } = useStaticQuery(
graphql`
query {
site {
siteMetadata {
title
author
}
}
}
`);
return (
<h1>
<Link className={headerStyles.title} to="/">
{site.siteMetadata.title}
</Link>
</h1>
);

Header 将是:

import * as React from "react";
import { UseSiteMetadata } from 'siteMetadata'


export default class Header extends React.Component {
render() {
return (<UseSiteMetadata /> )
}
}

关于typescript - useStaticQuery : Invalid hook call. Hooks只能在函数组件体内调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57343619/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com