为什么我会在控制台中遇到无效的挂钩错误?

发布于 2025-01-25 18:28:32 字数 1830 浏览 2 评论 0原文

我无法弄清自己的一生,为什么在通过React查询使用突变时会遇到此错误。任何形式的反馈都将不胜感激。

注意: 我正在使用函数(react)组件内部,因此我不确定为什么会丢弃此错误。

错误:

Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app

代码:

const addAsset = (asset) => {
    return axios.post('http://localhost/api/file-upload', asset);
}

const fileUpload = () => {
    const url = 'http://localhost/api/file-upload';

    let formData = new FormData();
    let imagefile = document.querySelector('#file');
    formData.append("image", imagefile.files[0]);

    const headers = {
        "Accept": 'application/json',
        "Authorization": `Bearer ${authToken}`
    }

    axios.post(url, formData, {headers})
        .then(resp => {
            let okStatus       = resp.status;
            let successMessage = resp.data.message;

            if(okStatus) {
                setShow(false);
            }

            setUploadSuccess(okStatus);
            setStatusMessage(successMessage);
            setStatusCode(okStatus);
        }).catch(error => {
        let errorMessage       = error.response.data.message;
        let errorStatus        = error.response.status;

        setStatusMessage(errorMessage);
        setStatusCode(errorStatus);
    });

    const queryClient = useQueryClient();

    return useMutation(addAsset, {
        onSuccess: () => {
            queryClient.invalidateQueries('uploads');
        }
    });
}

return(<Button variant="primary" onClick={fileUpload}>Upload!</Button>);

I cannot figure out for the life of me why I'm getting this error when using mutations via React Query. Any sort of feedback would be appreciated.

Note:
I'm using inside a function (React) component so I'm not sure why this error's getting thrown.

error:

Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app

code:

const addAsset = (asset) => {
    return axios.post('http://localhost/api/file-upload', asset);
}

const fileUpload = () => {
    const url = 'http://localhost/api/file-upload';

    let formData = new FormData();
    let imagefile = document.querySelector('#file');
    formData.append("image", imagefile.files[0]);

    const headers = {
        "Accept": 'application/json',
        "Authorization": `Bearer ${authToken}`
    }

    axios.post(url, formData, {headers})
        .then(resp => {
            let okStatus       = resp.status;
            let successMessage = resp.data.message;

            if(okStatus) {
                setShow(false);
            }

            setUploadSuccess(okStatus);
            setStatusMessage(successMessage);
            setStatusCode(okStatus);
        }).catch(error => {
        let errorMessage       = error.response.data.message;
        let errorStatus        = error.response.status;

        setStatusMessage(errorMessage);
        setStatusCode(errorStatus);
    });

    const queryClient = useQueryClient();

    return useMutation(addAsset, {
        onSuccess: () => {
            queryClient.invalidateQueries('uploads');
        }
    });
}

return(<Button variant="primary" onClick={fileUpload}>Upload!</Button>);

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

审判长 2025-02-01 18:28:32

正如错误消息所说,只能在功能组件的正文中调用钩子。他们无法在单击回调中被调用。您将需要将挂钩调用从FileUpload中移出。

const queryClient = useQueryClient();

const { mutate } = useMutation(addAsset, {
  onSuccess: () => {
    queryClient.invalidateQueries('uploads');
  }
});

const fileUpload = () => {
  const url = 'http://localhost/api/file-upload';
  // ...
  axios.post(url, formData, {headers})
     .then(
  // ...

  mutate(/* insert variables here */);
}

另请参见:挂钩规则

As the error message says, hooks can only be called in the body of a function component. They cannot be called in an onClick callback. You will need to move the hook calls out of fileUpload.

const queryClient = useQueryClient();

const { mutate } = useMutation(addAsset, {
  onSuccess: () => {
    queryClient.invalidateQueries('uploads');
  }
});

const fileUpload = () => {
  const url = 'http://localhost/api/file-upload';
  // ...
  axios.post(url, formData, {headers})
     .then(
  // ...

  mutate(/* insert variables here */);
}

See also: Rules of Hooks

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文