反应:组件属性未正确存储我想要的数据(来自查询) [英] React: An component attribute is not properly storing the data (from a query) that I want

查看:41
本文介绍了反应:组件属性未正确存储我想要的数据(来自查询)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近开始学习反应,遇到了一些我不理解的事情.因此,当我声明一个组件时,我也在构造函数中声明了一个属性.然后,在执行第一个查询(我正在使用Apollo客户端-GraphQL)之后,我要将结果(我知道它将始终是电子邮件)存储在声明的属性中,以便可以将其用作第二个查询中的参数.

I recently started learning react and I have encountered something that I do not understand. So when I declare a component I also declare an attribute in the constructor. Then, after executing the first query (I am using Apollo client - GraphQL ) I want to store the result (which I know that will be always an email) in the attribute declared so I can use it as a parameter in the second query.

该应用程序的逻辑是,我想显示给定电子邮件的所有订单,但首先我得到带有查询的电子邮件.

The app logic is that I want to show all the orders of a given email, but first I get the email with a query.

这是代码:

export default class Orders extends Component {
    constructor(){
        super();
        this.email = '';
      }

    render() {
        return (
            <div>
                <Query query = { GET_MAIL_QUERY }>
                {({data, loading}) => {
                    if (loading) return "Loading...";
                    this.email = data.me.email;
                    return <h1>{this.email}</h1>
                 }}

这时将返回包含电子邮件的标头,因此一切正常.但是,当我执行第二个查询(或尝试在第二个标题中显示电子邮件)时,似乎值存储不正确.

At this point a header containing the email is returned, so all good. But when I execute the second query (or try to display the email in the second header for that matter) it seems that the value is not properly stored.

                </Query>
                <h1>{this.email}</h1>
                <Query query = { GET_ORDERS_QUERY }
                variables = {{
                    email: this.email
                }}>
                    {({data, loading}) => {
                        if (loading) return "Loading...";
                        console.log(data);
                        let orders = data.ordersByEmail.data;
                        console.log(orders);
                        return orders.map(order =>
                            <div>
                                <h1>{order.date}</h1>
                                <h1>{order.price}</h1>
                                <h1>{order.conference.conferenceName}</h1>
                                <h1>{order.user.email}</h1>
                                <br></br>
                            </div>)
                    }}
                </Query>
            </div>
        )
    }
}
const GET_MAIL_QUERY = gql`
query getMyMail{
    me{
      email
    }
  }
`;  

const GET_ORDERS_QUERY = gql`
query getOrdersByEmail($email: String!) {
    ordersByEmail(email: $email) {
      data {
        gid
        date
        price
        user {
            email
          }
        conference{
            conferenceName
        }
      }
    }
  }
`;

我希望对此做一个解释,也可能希望找到一个解决方案(存储从查询返回的值以在另一个查询中使用)

I would love an explanation for this and maybe a solution (to store a value returned from a query to use it in another)

感谢您的期待:)

推荐答案

以我的经验,您应该使用从 @ apollo/react-hooks 导入的 useQuery 和功能组件因为它易于使用,所以可以使您的代码更简洁

In my experience, you should use useQuery imported from @apollo/react-hooks with functional component because it's easy to use, it makes your code more cleaner

如果您想将< Query/> 组件与类component一起使用,则可以.但是,如果要存储从服务器接收到的数据,则应在构造函数的状态下创建一个变量,并且要更新为状态时,应使用 this.setState({email:data.me.email}).不要使用 this.state.email = data.me.email ,它是反模式,当您使用它更新状态时,React不会触发重新渲染.

If your want to use <Query/> component with class component, it's ok. But, if you want to store data received from server, you should create a variable in state of constructor and when you want to update to state, you should use this.setState({email: data.me.email}). Don't use this.state.email = data.me.email, it's anti-pattern, React will not trigger re-render when you use it to update your state.

这是代码:

import React, { useState } from 'react'
import gql from 'graphql-tag'
import { useQuery, useMutation } from '@apollo/react-hooks'

const GET_MAIL_QUERY = gql`
	query getMyMail {
		me {
			email
		}
	}
`

const GET_ORDERS_QUERY = gql`
	query getOrdersByEmail($email: String!) {
		ordersByEmail(email: $email) {
			data {
				gid
				date
				price
				user {
					email
				}
				conference {
					conferenceName
				}
			}
		}
	}
`

const Orders = () => {
	const [email, setEmail] = useState('')
	const { data: getMailQueryData, loading, error } = useQuery(GET_MAIL_QUERY, {
		onCompleted: data => {
			setEmail(data.me.email)
		},
		onError: err => alert(err),
	})
	const { data: getOrdersQueryData } = useQuery(GET_ORDERS_QUERY, {
		variables: { email: email },
	})

	if (loading) return <div>Loading...</div>
	if (error) return <div>Error...</div>
	return ...
}

这篇关于反应:组件属性未正确存储我想要的数据(来自查询)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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