2

我有一个 React 组件,它调用一个期望接收对象数组(用于验证数据)的查询。然后我使用它来验证一个 html 表单,该表单又在 apollo Mutation 元素中定义。它在组件方法的 return 语句中的结构render()方式可行,但看起来很麻烦,让我想起了回调地狱时代。我真正想做的是摆脱方法中的<QueryCustomerValidations>元素render()并将其移动到(理想情况下)componentDidMount生命周期事件中。这样验证器就可以在那里加载以供以后在表单中使用,然后离开<MutationCreateCustomer>内部的 render()。

现在,我必须将表单包装在突变中。查询返回的箭头函数内部的突变,以便以正确的顺序接收异步数据。

    //-------------------------------------------------------------------------
    // Component Lifecycle Eventhandler Methods
    //-------------------------------------------------------------------------
    componentDidMount()
    {

    }    


    //-------------------------------------------------------------------------
    // Render Method Section
    //-------------------------------------------------------------------------
    public render(): JSX.Element
    {
        // Return Form
        return (
            <React.Fragment>
                {/* PAGE TITLE  */}
                <h2 className="text-center mb-3">Agregar Nuevo Cliente</h2>

                {/* LOAD VALIDATIONS INTO STATE  */}
                <QueryCustomerValidations
                    query={Q_GET_CUSTOMER_VALIDATIONS}
                >
                    {({ loading: loadingValidations, error: errorValidations, data: dataValidations }) =>
                    {
                        if (loadingValidations)
                        {
                            return "Cargando..."
                        }
                        if (errorValidations)
                        {
                            return `Error: ${errorValidations.message}`
                        }
                        if (dataValidations)
                        {
                            const validators: ValidationDescriptor[] = []
                            dataValidations.getCustomerValidations.forEach((validator) => {
                                validators.push(validator as ValidationDescriptor)
                            })
                            this.validators.setValidators(validators)
                        }

                        /* DATA ENTRY FORM  */
                        return (
                            <div className="row justify-content-center">

                                <MutationCreateCustomer 
                                    mutation={M_CREATE_CUSTOMER}
                                    onCompleted={() => this.props.history.push('/')}
                                >
                                    {(createCustomer: any) => {
                                        return (                                            
                                            <form name="frmNewCustomer"
                                                    className="col-md-8 m-3"
                                                    onSubmit={e => this.frmNewCustomer_submit(e, createCustomer)}
                                            >

                                                { this.ctrl_form_layout(this.props, this.state, this.validators) }

                                            </form>
                                        )
                                    }}
                                </MutationCreateCustomer>
                            </div>
                        )
                    }}

                </QueryCustomerValidations>

            </React.Fragment>
        );
    }

出于文档目的,这里是创建查询的接口。由于我使用 apollo 客户端从服务器获取了其中的一些数据,因此在这种情况下,一个简单的 graphql 查询解决方案onDidMount()将不起作用。

getCustomerValidations.ts (Interfaces)


// ====================================================
// GraphQL query operation: getCustomerValidations
// ====================================================

export interface getCustomerValidations_getCustomerValidations {
  __typename: "ValidationDescriptor";
  field: string | null;
  type: string | null;
  required: boolean;
  max: number | null;
  min: number | null;
  regex: string | null;
}

export interface getCustomerValidations {
  getCustomerValidations: getCustomerValidations_getCustomerValidations[];
}

customer-validations.query.ts (Client side query types)


//---------------------------------------------------------------------------------
// Imports Section (React/Apollo Libs)
//---------------------------------------------------------------------------------
import { gql }                              from 'apollo-boost';
import { Query }                            from 'react-apollo'

import { getCustomerValidations }            from '../../typeDefs/operations/getCustomerValidations'

//---------------------------------------------------------------------------------
// GQL Query: Customers
//---------------------------------------------------------------------------------
export const Q_GET_CUSTOMER_VALIDATIONS = gql`
    query getCustomerValidations {
        getCustomerValidations
        {
            field
            type
            required
            max
            min
            regex
        }
    }
`;

//---------------------------------------------------------------------------------
// Query Class: Customers
//---------------------------------------------------------------------------------
export class QueryCustomerValidations extends Query<getCustomerValidations> { }


正确的解决方案可以是一种从方法中复制并触发<QueryCustomerValidations>元素的componentDidMount()方法,或者如何将元素从方法中取出render()并使用某种“等待”方式调用它,以便可以首先调用它以及之后的突变(并使用查询中的数据)。

谢谢,我知道这不是很容易弄清楚。

4

1 回答 1

2

您正在寻找此处此处此处描述的“旧”(在<Query/>组件之前使用)HOC 模式(带有) 。compose

将在开始时请求的“graphql(gql query ...”(不带条件skip选项)与一个或多个(命名的)“gql mutation ...”(按需调用)组合在一起,可以为您提供一个清晰易读的解决方案。

compose(
  graphql(Q_GET_CUSTOMER_VALIDATIONS),
  graphql(gql`mutation { ... }`, { name: 'createSth' })
)(SomeComponent)

将传递datacreateSth道具<SomeComponent/>然后this.props.data对象将包含loading,errorgetCustomerValidations字段/属性。它在这里描述。

查询将在开始时调用(您可以true在 中this.props.data.loading),无需在cDM(). 可以使用this.props.createSth()- 上面定义的自定义名称(而不是默认道具名称mutate)运行突变。

当然,您可以将它们与其他必需的 HOC、fe reduxconnect()等混合使用withFormik()——只需添加一行代码。

于 2019-05-27T09:07:00.980 回答