问题
我正在尝试使用阿波罗从带有graphql的wordpress中获取数据。 在这种情况下,将useQuery()中的数据值设置为undefined后即可检索。
相应的源代码
我的ApolloClient和提供程序设置如下:
BlogList.jsx
import React from 'react'
import ApolloClient, {gql, InMemoryCache} from "apollo-boost";
import { ApolloProvider, useQuery } from "@apollo/react-hooks"
import PostLayout from '../components/PostLayout'
const client = new ApolloClient({
uri: "https://localhost.info/graphql",
cache
});
export const POSTS_QUERY = gql`
{
posts {
nodes {
id
title
content
uri
date
}
}
}
`
const Posts = () => {
const { loading, error, data } = useQuery(POSTS_QUERY);
console.log(data)
if (loading) return <p>Loading Posts...</p>
if (error) return <p> {data}Something wrong happened!</p>
if (data === undefined) return <p>ERROR</p>
return (
<pre>{data}test</pre>
);
};
const BlogList = () => {
const blogClassName = 'p-blog'
return (
<PostLayout>
<ApolloProvider client={client}>
<h1>My First Apollo Theme!</h1>
<Posts />
</ApolloProvider>
</PostLayout>
)
}
export default BlogList
index.jsx
import React from 'react'
import Layout from 'components/Layout'
import SEO from 'components/SEO'
import 'scss/layout/index.scss'
import 'scss/object/project/_top.scss'
import Content from '../components/Content'
import BlogList from '../templates/BlogList'
class IndexPage extends React.Component<IndexProps, showState> {
constructor(props: showState) {
const post: boolean = props.pageContext.post
super(props)
this.state = {
showContent: post ? post : false,
tabType: post ? props.pageContext.node.categories[0].name : '',
props: this.props,
post: post ? post : false,
}
this.clickShowContent = this.clickShowContent.bind(this)
this.clickShowPost = this.clickShowPost.bind(this)
}
clickShowContent(type: string) {
this.setState({
showContent: !this.state.showContent,
tabType: type,
})
}
clickShowPost() {
this.setState({
post: true ? false : true,
})
}
render() {
const topClassName = 'p-top'
const menuClassName = 'l-menu'
return (
<Layout>
<SEO />
<nav className={`${menuClassName}__blocks`} id="js-topMenu">
<button
onClick={() => this.clickShowContent(TAB_TYPES.BLOG)}
className={`js-btnBlog js-topBtn ${topClassName}__blogBlock ${menuClassName}__block`}
>
<div className={`${topClassName}__blogContainer`}>
<div
className={`${menuClassName}Blog ${menuClassName}__subHeading ${menuClassName}--blog`}
>
Blog
</div>
</div>
</button>
</nav>
</div>
{this.state.showContent ? (
<PostContext.Provider value={this.state}>
<BlogList />
</PostContext.Provider>
) : null}
</Layout>
)
}
}
export default IndexPage
结果
查看BlogList
undefined
{posts: {…}}
我想要实现的目标。
我希望能够获得{posts:{...}}而不是未定义的数据。