首页 > 解决方案 > 错误:无效的挂钩调用。钩子只能在函数组件的主体内部调用。【我还在用函数组件】

问题描述

我正在关注有关构建 Shopify 应用程序的教程,但出现错误:

无效的挂钩调用。

错误发生在useMutation

const Index = () => {
  const [updateProduct] = useMutation(PRODUCT_UPDATER);
  const submitHandler = useCallback(() => {
    let count = 0;
    const runMutation = (product) => {
      updateProduct({
        variables: {
          input: {
            descriptionHtml: `${product.descriptionHtml}${descriptionValue}`,
            title: `${product.title}${titleValue}`,
            id: product.id,
          },
        },
      }).then((data) => {
        console.log('Update Product', count, data);
        count++;
        if (products[count]) runMutation(products[count]);
        else {
          console.log('Update Complete');
        }
      });
    };
    runMutation(products[count]);
  }, [products, descriptionValue, titleValue]);
  return (
    <Page>
      <Card>
        <TextField label="Title" value={titleValue} onChange={setTitleValue} />
        <TextField label="Description" value={descriptionValue} onChange={setDescriptionValue} />
        <ResourcePicker
          resourceType="Product"
          showVariants={false}
          open={pickerOpen}
          onSelection={(resource) => {
            console.log(resource);
            setProducts(resource.selection);
          }}
        />
        <DataTable
          columnContentTypes={['text', 'text', 'text', 'text', 'text']}
          headings={['ID', 'Old title', 'New title', 'Old description', 'New description']}
          rows={productTableDisplayData}
        />
        <Button primary disabled={!productTableDisplayData.length} onClick={submitHandler}>
          Submit
        </Button>
      </Card>
    </Page>
  );
};

export default Index;

我没有发布graphql 突变,因为我认为这只是一个钩子问题。

标签: node.jsreactjsexpressgraphqlshopify-app

解决方案


你应该在 useCallback 之后返回一些 jsx

如果这是一个钩子,则将其重命名为 useIndex,或名称前带有 use 的任何内容


推荐阅读