[英]How do I do dynamic routing with Next.js based on slug from GraphQL API?
[英]Dynamic routing using graphQL in a Next.js app
我正在使用 apollo 作为客户端构建一个使用 spaceX graphQL api 的网页。 在登陆页面上,我想显示一个“发布”卡片,点击该卡片后,将指向一个新页面,其中包含有关该特定发布的详细信息,如下所示:
index.js
import { ApolloClient, InMemoryCache, gql } from "@apollo/client"
import Link from 'next/link'
export const getStaticProps = async () => {
const client = new ApolloClient({
uri: 'https://api.spacex.land/graphql/',
cache: new InMemoryCache()
})
const { data } = await client.query({
query: gql`
query GetLaunches {
launchesPast(limit: 10) {
id
mission_name
launch_date_local
launch_site {
site_name_long
}
links {
article_link
video_link
mission_patch
}
rocket {
rocket_name
}
}
}
`
});
return {
props: {
launches: data.launchesPast
}
}
}
export default function Home({ launches }) {
return (
<div>
{launches.map(launch => {
return(
<Link href = {`/items/${launch.id}`} key = {launch.id}>
<a>
<p>{launch.mission_name}</p>
</a>
</Link>
)
})}
</div>
)
}
我设置了一个新页面items/[id].js
来显示有关各个启动的信息,但这就是混乱的地方。 Using a standard REST api I'd simply use fetch
, then append the id to the end of the url to retrieve the desired data. 但是,我不确定如何使用getStaticPaths
function 在 graphQL 中进行等效操作。 有什么建议么?
这是items/[id]/js
,我试图在其中呈现单个启动数据:
import { ApolloClient, InMemoryCache, gql } from "@apollo/client"
export const getStaticPaths = async () => {
const client = new ApolloClient({
uri: "https://api.spacex.land/graphql/",
cache: new InMemoryCache(),
});
const { data } = await client.query({
query: gql`
query GetLaunches {
launchesPast(limit: 10) {
id
}
}
`,
});
const paths = data.map((launch) => {
return {
params: { id: launch.id.toString() },
};
});
return {
paths,
fallback:false
}
};
export const getStaticProps = async (context) => {
const id = context.params.id
// not sure what to do here
}
const Items = () => {
return (
<div>
this is items
</div>
);
}
export default Items;
对于 getStaticPaths
export const getStaticPaths = async () => {
const { data } = await client.query({
query: launchesPastQuery, // this will query the id only
});
return {
paths: data.CHANGE_THIS.map((param) => ({
params: { id: param.id },
})),
fallback: false,
};
};
CHANGE_THIS是遵循 JSON 响应中的数据的查询类型。
对于 getStaticProps
export const getStaticProps = async ({
params,
}) => {
const { data } = await client.query({
query: GetLaunchPastByID ,
variables: { LaunchID: params.id, idType: "UUID" }, // the idType is optional, and the LaunchID is what you'll use for querying by it*
});
return {
props: {
launchesPast: data.CHANGE_THIS,
},
};
launchPastQueryByID 是这样的:
const GetLaunchPastByID = gql`
query LaunchPastByID($LaunchID: UUID!) { // UUID is id type
CHANGE_THIS(id: $LaunchID) {
id
//...
}
}
`;
抱歉没有给您正确的查询,spacex.land 目前已关闭。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.