代码之家  ›  专栏  ›  技术社区  ›  pellea

使用react apollo,如何使用TypeScript在同一组件中定义2个突变?

  •  3
  • pellea  · 技术社区  · 7 年前

    使用以下各项 issue on GitHub 我可以让一个突变 类型脚本 。但我没有找到在同一组分中使用2个突变的方法。

    只有一个 mutate() 作用于 this.props .

    我们必须如何键入组件以使其理解 name 传递给graphql的选项?

    graphql<ContainerProps, {}, string, ContainerProps>(gql`... `, { name: 'deleteData' });
    graphql<ContainerProps, {}, string, ContainerProps>(gql`...`, { name: 'createData' });
    

    编辑: 如果两个突变具有相同的参数名称(a string 已命名 id 例如),我们真的需要将这些参数包装成显式类型吗?

    编辑2: 我有一个例外 { name: 'xxx' } :

    类型错误:\u此错误。道具。mutate不是一个函数

    如果我只声明一个突变(没有name选项),那么它工作正常。

    2 回复  |  直到 7 年前
        1
  •  1
  •   pellea    7 年前

    根据Miro Lehtonen提供的链接,这里是对我有用的。

    type MutationProps = {
        create: MutationFunc<IResponse, ICreateVariables>;
        delete: MutationFunc<IResponse, IDeleteVariables>;
    };
    
    type ContainerProps = OtherQueryProps & MutationProps;
    
    const withCreate =
        graphql<ContainerProps, IResponse, ICreateVariables, ContainerProps>(
            CreateMutation,
            {
                // tslint:disable-next-line:no-any
                props: ({ mutate, ...rest }): any => ({
                    ...rest,
                    create: mutate
                })
            });
    

    删除突变的代码相同。

    代码正在运行,但我不喜欢 any 在里面。我没有找到正确键入道具的方法,我也不认为我返回了正确的类型(尽管它工作得很好)。欢迎提出任何建议(关于如何删除 任何 ).

        2
  •  0
  •   Miro Lehtonen    7 年前

    突变的默认名称为 mutate 您可以通过 props.mutate 。如果你想在同一个成分中有更多的突变,你需要给它们命名,比如 deleteData createData 。可通过 props.deleteData props.createData .

    一个好的做法是命名所有的突变,只是为了让代码更容易阅读。作为通用名称, 变异 不是很有描述性。