问题
I'm trying to get values via useStaticQuery
from gatsby-config.js.
My codes are the followings.
Could anyone have any ideas to solve this issue?
Thank you in advance
repo
https://github.com/koji/portfolio
package.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"
}
siteMetadata.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"
}
}
回答1:
the first letter in the name of the component not capitalized and it causing this problem;
and useStaticQuery
doesn't work like that, you need to render the component's children that depend on this query inside the component you use it there;
the component UseSiteMetadata will be :
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>
);
and the Header
will be :
import * as React from "react";
import { UseSiteMetadata } from 'siteMetadata'
export default class Header extends React.Component {
render() {
return (<UseSiteMetadata /> )
}
}
来源:https://stackoverflow.com/questions/57343619/usestaticquery-invalid-hook-call-hooks-can-only-be-called-inside-of-the-body-o