如何在Gatsby的JSX代码中定义并使用局部变量meta?
Hey there! I see you're trying to streamline your Gatsby component by using a local variable instead of repeating data.site.siteMetadata everywhere—smart move! Let's break down why your current approach isn't working and fix it.
Why Your Second Code Snippet Fails
In JSX, the curly braces {} are meant to hold expressions (pieces of code that return a value), not statements like variable declarations (var, const, let). When you write {var meta=data.site.siteMetadata}, you're trying to run a declaration statement directly in JSX, which throws an error because that's not allowed in JSX's expression context.
Working Solutions
Solution 1: Declare the Variable in the Component Function Body
The simplest, most readable fix is to move your variable declaration outside the JSX, in the main function body of your component:
import React from "react" import { graphql } from "gatsby" export default ({ data }) => { // Declare your variable here, in the function body (allowed!) const meta = data.site.siteMetadata; return ( <div> <h1>About {meta.title}</h1> <p>We're a very cool website you should return to often.</p> </div> ) } export const query = graphql` query { site { siteMetadata { title } } } `
Solution 2: Destructure Directly in the Component Parameters
If you want to keep things extra concise, you can destructure the siteMetadata directly from the data prop when defining your component. This eliminates the need for an extra variable declaration entirely:
import React from "react" import { graphql } from "gatsby" // Destructure `meta` directly from the incoming data prop export default ({ data: { site: { siteMetadata: meta } } }) => ( <div> <h1>About {meta.title}</h1> <p>We're a very cool website you should return to often.</p> </div> ) export const query = graphql` query { site { siteMetadata { title } } } `
(Not Recommended) Use an IIFE for Inline Variable Declaration
While this works, it's not ideal because it makes your JSX harder to scan and maintain. I'm including it just for completeness:
import React from "react" import { graphql } from "gatsby" export default ({ data }) => ( <div> {/* Wrap the variable declaration in an immediately-invoked function expression */} {(() => { const meta = data.site.siteMetadata; return <h1>About {meta.title}</h1>; })()} <p>We're a very cool website you should return to often.</p> </div> ) export const query = graphql` query { site { siteMetadata { title } } } `
Final Notes
Stick with Solution 1 or 2—they're the most readable and maintainable options. Solution 1 is great if you need to reuse the meta variable multiple times in your component, while Solution 2 is perfect for one-off uses or keeping your component's return block as clean as possible.
内容的提问来源于stack exchange,提问作者Shatiz

