无法使用 react.js 呈现 graphql 数据
Not able to render graphql data with react.js
我正在尝试使用 apollo 客户端、服务器、ReactJS 和 NodeJS 显示来自 API 的值,下面是执行此操作的代码:
客户:
UserPosts.js:
import { useMutation, useQuery } from "@apollo/client";
import { USERPostedImages } from "./query";
function UserPosts() {
const { loading, error, data } = useQuery(USERPostedImages);
return (
<div className="App">
{data.userPostedImages.map((data) => (
<>
<p key={data.posterName}>
{data.url}----{data.description}
</p>
</>
))}
</div>
);
}
export default UserPosts;
query.js 对于 graphql 查询:
import { gql } from "@apollo/client";
export const unsplashImages = gql`
{
unsplashImages {
url
posterName
description
}
}
`;
export const USERPostedImages = gql`
{
userPostedImages {
url
posterName
description
}
}
`;
App.js:
import React from 'react';
import {NavLink, BrowserRouter as Router, Route} from 'react-router-dom';
import UserPosts from './components/UserPosts';
import Bin from './components/Bin';
import Home from './components/Home';
import NewPost from './components/NewPost';
import UnsplashPosts from './components/UnsplashPosts';
import {
ApolloClient,
HttpLink,
InMemoryCache,
ApolloProvider
} from '@apollo/client';
const client = new ApolloClient({
cache: new InMemoryCache(),
link: new HttpLink({
uri: 'http://localhost:4000'
})
});
function App() {
return (
<ApolloProvider client={client}>
<Router>
<div>
<header className='App-header'>
<h1 className='App-title'>
GraphQL Lab5
</h1>
<nav>
<NavLink className='navlink' to='/'>
Home
</NavLink>
<NavLink className='navlink' to='/my-bin'>
Bin
</NavLink>
<NavLink className='navlink' to='/my-posts'>
Posts
</NavLink>
<NavLink className='navlink' to='/new-post'>
Create New Post
</NavLink>
</nav>
</header>
<Route exact path='/' component={UnsplashPosts} />
<Route path='/my-bin/' component={Bin} />
<Route path='/my-posts' component={UserPosts} />
<Route path='/new-post' component={NewPost} />
</div>
</Router>
</ApolloProvider>
);
}
export default App;
服务器
index.js:
const {ApolloServer, gql} = require('apollo-server');
const axios = require('axios');
const uuid = require('uuid');
const bluebird = require('bluebird');
const redis = require('redis')
const client = redis.createClient();
bluebird.promisifyAll(redis.RedisClient.prototype);
bluebird.promisifyAll(redis.Multi.prototype);
const typeDefs = gql`
type Query {
photos: [Photo]
post: [ImagePost]
unsplashImages: [ImagePost]
userPostedImages: [ImagePost]
}
type Photo {
id: String
username: String
}
type ImagePost {
id: String!
url: String!
posterName: String!
description: String
userPosted: Boolean
binned: Boolean
}
type Mutation {
uploadImage(
url: String!
description: String
posterName: String
): ImagePost
}
`;
const resolvers = {
Query: {
unsplashImages: async (_, args) => {
const { data } = await axios.get('https://api.unsplash.com/photos/?client_id=2zceQd7D4SraKoqW_GjPzXboSup3TKRIPk7EXfJBcAs');
const a = data.map(imagePost => {
return {
id: imagePost.id,
posterName: imagePost.user.name,
url: imagePost.urls.raw,
description: imagePost.description,
}
})
return a;
},
userPostedImages: async (_,args) => {
let history = await client.lrangeAsync("postedImagesList",0,100).map(JSON.parse);
return history;
}
},
Mutation: {
uploadImage: async (_,args) => {
//const { data } = await axios.get('https://api.unsplash.com/photos/?client_id=2zceQd7D4SraKoqW_GjPzXboSup3TKRIPk7EXfJBcAs');
const newPost = {
id: uuid.v4(),
url: args.url,
description: args.description,
posterName: args.posterName,
binned: false,
userPosted: true,
}
await client.lpushAsync("postedImagesList",JSON.stringify(newPost));
}
}
};
const server = new ApolloServer({typeDefs, resolvers});
server.listen().then(({url}) => {
console.log(` Server ready at ${url} `);
});
当我 运行 我的客户出现以下错误时:
Uncaught TypeError: Cannot read properties of undefined (reading 'userPostedImages')
at UserPosts (UserPosts.js:22:1)
我不确定自己做错了什么,我的服务器工作正常并且能够在 graphql playground 中看到数据,但客户端上没有任何显示。
data
尚不可用 (null
),因为它仍在获取,因此要处理此问题,请使用具有 loading
值的条件渲染。
const { loading, error, data } = useQuery(USERPostedImages);
if(error) {
return <h1> error</h1>;
}
if(loading) {
return <h1> loading</h1>;
}
....
我正在尝试使用 apollo 客户端、服务器、ReactJS 和 NodeJS 显示来自 API 的值,下面是执行此操作的代码:
客户:
UserPosts.js:
import { useMutation, useQuery } from "@apollo/client";
import { USERPostedImages } from "./query";
function UserPosts() {
const { loading, error, data } = useQuery(USERPostedImages);
return (
<div className="App">
{data.userPostedImages.map((data) => (
<>
<p key={data.posterName}>
{data.url}----{data.description}
</p>
</>
))}
</div>
);
}
export default UserPosts;
query.js 对于 graphql 查询:
import { gql } from "@apollo/client";
export const unsplashImages = gql`
{
unsplashImages {
url
posterName
description
}
}
`;
export const USERPostedImages = gql`
{
userPostedImages {
url
posterName
description
}
}
`;
App.js:
import React from 'react';
import {NavLink, BrowserRouter as Router, Route} from 'react-router-dom';
import UserPosts from './components/UserPosts';
import Bin from './components/Bin';
import Home from './components/Home';
import NewPost from './components/NewPost';
import UnsplashPosts from './components/UnsplashPosts';
import {
ApolloClient,
HttpLink,
InMemoryCache,
ApolloProvider
} from '@apollo/client';
const client = new ApolloClient({
cache: new InMemoryCache(),
link: new HttpLink({
uri: 'http://localhost:4000'
})
});
function App() {
return (
<ApolloProvider client={client}>
<Router>
<div>
<header className='App-header'>
<h1 className='App-title'>
GraphQL Lab5
</h1>
<nav>
<NavLink className='navlink' to='/'>
Home
</NavLink>
<NavLink className='navlink' to='/my-bin'>
Bin
</NavLink>
<NavLink className='navlink' to='/my-posts'>
Posts
</NavLink>
<NavLink className='navlink' to='/new-post'>
Create New Post
</NavLink>
</nav>
</header>
<Route exact path='/' component={UnsplashPosts} />
<Route path='/my-bin/' component={Bin} />
<Route path='/my-posts' component={UserPosts} />
<Route path='/new-post' component={NewPost} />
</div>
</Router>
</ApolloProvider>
);
}
export default App;
服务器
index.js:
const {ApolloServer, gql} = require('apollo-server');
const axios = require('axios');
const uuid = require('uuid');
const bluebird = require('bluebird');
const redis = require('redis')
const client = redis.createClient();
bluebird.promisifyAll(redis.RedisClient.prototype);
bluebird.promisifyAll(redis.Multi.prototype);
const typeDefs = gql`
type Query {
photos: [Photo]
post: [ImagePost]
unsplashImages: [ImagePost]
userPostedImages: [ImagePost]
}
type Photo {
id: String
username: String
}
type ImagePost {
id: String!
url: String!
posterName: String!
description: String
userPosted: Boolean
binned: Boolean
}
type Mutation {
uploadImage(
url: String!
description: String
posterName: String
): ImagePost
}
`;
const resolvers = {
Query: {
unsplashImages: async (_, args) => {
const { data } = await axios.get('https://api.unsplash.com/photos/?client_id=2zceQd7D4SraKoqW_GjPzXboSup3TKRIPk7EXfJBcAs');
const a = data.map(imagePost => {
return {
id: imagePost.id,
posterName: imagePost.user.name,
url: imagePost.urls.raw,
description: imagePost.description,
}
})
return a;
},
userPostedImages: async (_,args) => {
let history = await client.lrangeAsync("postedImagesList",0,100).map(JSON.parse);
return history;
}
},
Mutation: {
uploadImage: async (_,args) => {
//const { data } = await axios.get('https://api.unsplash.com/photos/?client_id=2zceQd7D4SraKoqW_GjPzXboSup3TKRIPk7EXfJBcAs');
const newPost = {
id: uuid.v4(),
url: args.url,
description: args.description,
posterName: args.posterName,
binned: false,
userPosted: true,
}
await client.lpushAsync("postedImagesList",JSON.stringify(newPost));
}
}
};
const server = new ApolloServer({typeDefs, resolvers});
server.listen().then(({url}) => {
console.log(` Server ready at ${url} `);
});
当我 运行 我的客户出现以下错误时:
Uncaught TypeError: Cannot read properties of undefined (reading 'userPostedImages')
at UserPosts (UserPosts.js:22:1)
我不确定自己做错了什么,我的服务器工作正常并且能够在 graphql playground 中看到数据,但客户端上没有任何显示。
data
尚不可用 (null
),因为它仍在获取,因此要处理此问题,请使用具有 loading
值的条件渲染。
const { loading, error, data } = useQuery(USERPostedImages);
if(error) {
return <h1> error</h1>;
}
if(loading) {
return <h1> loading</h1>;
}
....