【问题标题】:Using react-apollo, how to define 2 mutations in the same component with TypeScript?使用 react-apollo,如何使用 TypeScript 在同一个组件中定义 2 个突变?
【发布时间】:2018-08-11 03:58:02
【问题描述】:

使用以下 issue on GitHub 我可以使一个突变与 Typescript 一起工作。但是我没有找到在同一个组件中使用 2 个突变的方法。

this.props 中只有一个mutate() 函数。

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

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

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

编辑 2: 当我使用 { name: 'xxx' } 声明 2 个突变时,我遇到了这个异常:

TypeError: _this.props.mutate 不是函数

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

【问题讨论】:

    标签: reactjs typescript apollo react-apollo


    【解决方案1】:

    突变的默认名称是mutate,您可以通过props.mutate 访问它。如果你想在同一个组件中有更多的突变,你需要给它们命名,比如deleteDatacreateData。这些可通过props.deleteDataprops.createData 访问。

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

    【讨论】:

    【解决方案2】:

    根据 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。我没有找到正确键入道具的方法,并且我认为我没有返回正确的类型(尽管它工作正常)。非常欢迎任何建议(关于如何删除any)。

    【讨论】:

      猜你喜欢
      • 2019-09-19
      • 2021-12-13
      • 2019-11-28
      • 2018-09-02
      • 2020-03-11
      • 2017-01-15
      • 2018-09-01
      • 1970-01-01
      • 2019-02-02
      相关资源
      最近更新 更多