尝试使用 Apollo GraphQL 的 useQuery 从 Strapi v4 (PostgreSQL) 获取本地化内容。当
locale
值被硬编码时它可以正常工作,但当它作为变量传递时则不行。 文档。
示例#1(这个可行):
export const GET_CATS = gql`
query GetCategories {
categories( locale: "en") {
data {
id
attributes {
title
}
}
}
}
`;
注意:以上也适用于其他语言环境,例如“德”。
示例#2(不起作用):
export const GET_CATS = gql`
query GetCategories($locale: String) {
categories( locale: $locale ) {
data {
id
attributes {
title
}
}
}
}
export function useCategories() {
const { data, loading, error } = useQuery(GET_CATS, {
variables: { locale: 'en' },
notifyOnNetworkStatusChange: true,
});
return { data, loading, error };
}
`;
错误:
[ApolloError:响应不成功:收到状态代码 400]
示例#3(这个可行): 这里我使用
filters:
,变量有效:
export const GET_CATS = gql`
query GetCategories($locale: String) {
categories(filters:{ locale: { eq: $locale }}) {
data {
id
attributes {
title
}
}
} } `;
export function useCategories() {
const { data, loading, error } = useQuery(GET_CATS, {
variables: { locale: 'en' },
notifyOnNetworkStatusChange: true,
});
return { data, loading, error }; }
但是在这种情况下,如果我使用任何其他变量作为语言环境,例如
locale: "de"
,查询返回一个空数组。可能是因为并非所有类别都翻译为“de”?但为什么“de”在示例#1 中成功返回翻译内容?
想通了。需要使用
I18NLocaleCode!
而不是 String
作为变量类型:
query Categories($id: ID, $locale: I18NLocaleCode!) {
...
}