简体   繁体   English

从 React 中的 GraphQL 查询中获取数据

[英]Get the data from GraphQL query in React

I'm sorry if this is something obvious, I just don't get it.如果这是显而易见的事情,我很抱歉,我只是不明白。 I'm trying to get data from GraphQL server.我正在尝试从 GraphQL 服务器获取数据。 I'm following the docs on Apollo client and everything's fine.我正在关注Apollo客户端上的文档,一切都很好。 The problem is that I keep getting the data in the form of a promise, rather than a real object问题是我一直以 promise 的形式获取数据,而不是真正的 object

 const GET_DATA = gql` { category { name products { name inStock } } } `; const data = client.query({ query: GET_DATA, }).then((result) => { return result; }).then((res) => res.data); ReactDOM.render( <ApolloProvider client={client}> <React.StrictMode> <App data={data} /> </React.StrictMode> </ApolloProvider>, document.getElementById("root") );

I tried chaining another.then() method and converting the response with.json() method, it didn't work.我尝试链接 another.then() 方法并使用 .json() 方法转换响应,它没有用。 Maybe because GraphQL responses are different?也许是因为 GraphQL 响应不同?

I would use useQuery() hook but I'm specifically asked to work with Class Components我会使用useQuery()钩子,但我被特别要求使用 Class 组件

That data const variable will hold a promise, but the result you get from GraphQl should be the correct one, in the first.then block you need to save the result in a state, then return that state as data to your App component.data常量变量将保存 promise,但您从 GraphQl 获得的结果应该是正确的,在 first.then 块中,您需要将结果保存在 state 中,然后将该 state 作为数据返回到您的 App 组件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM