从 GraphQL 查询数据后如何将数据存储在 React 状态? [英] How to store the data in React state after Querying it from GraphQL?

查看:23
本文介绍了从 GraphQL 查询数据后如何将数据存储在 React 状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我的查询:

从'react'导入React;从'../queries/getProduct'导入getProducts;从react-apollo"导入{查询};export const Product = () =>{const proId = {"productId": "95eb601f2d13"}返回 (<查询查询={getProducts}变量={proId}>{({ 加载,错误,数据 }) =>{if (loading) return "Loading...";如果(错误)返回`错误!${error.message}`;返回 (<div>{data.map(entry => entry)}

);}}</查询>);};导出默认产品;

我现在需要将接收到的数据存储在 React 或 Redux(以最理想的为准)中,以便我可以在 1/2 组件中访问该数据.如何存储数据而不是像上面那样渲染数据?

根据这些数据,我渲染了 90% 的组件.

解决方案

像这样尝试 onCompleted:

function onCompletedHandler(data) {dispatch({ 'RECEIVED_DATA': 数据 })}<Query query={getProducts} variables={proId} onCompleted={onCompletedHandler}>...</查询>

Following is my Query:

import React from 'react';
import getProducts from '../queries/getProduct';
import { Query } from "react-apollo";


export const Product = () => {
    const proId = {
        "productId": "95eb601f2d13"
    }

   return (
       <Query query={getProducts} variables={proId}>
        {({ loading, error, data }) => {
            if (loading) return "Loading...";
            if (error) return `Error! ${error.message}`;

            return (
                <div>
                    {data.map(entry => entry)}
                </div>
            );
        }}
       </Query>
   );
};

export default Product;

I need to now store the received data in React or Redux (whichever is ideal) so I can access that data in 1/2 Components. How can I store data rather than rendering it like it's doing above?

Depending on this data, I am rendering 90% components.

解决方案

Try onCompleted like so:

function onCompletedHandler(data) {
    dispatch({ 'RECEIVED_DATA': data })
}

<Query query={getProducts} variables={proId} onCompleted={onCompletedHandler}>
    ...
</Query>

这篇关于从 GraphQL 查询数据后如何将数据存储在 React 状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆