简体   繁体   English

React 挂钩中的 Axios 实例“无法读取未定义的属性 'get'”

[英]Axios instance in React hook “Cannot read property 'get' of undefined”

The axios instance is not yet ready upon render as I get the error "Cannot read property 'get' of undefined", BUT the branches are loaded, so apparently next attempt succeeds. axios 实例在渲染时尚未准备好,因为我收到错误“无法读取未定义的属性'get'”,但分支已加载,因此显然下一次尝试成功。

The axios instance in hooks.js : hooks.js 中的hooks.js实例:

import {useState, useEffect} from 'react';
import axios from 'axios';
import {useKeycloak} from '@react-keycloak/web';
import {BASE_URL} from '../constants.js';

export const useAxios = () => {
    const {keycloak, initialized} = useKeycloak();
    const [axiosInstance, setAxiosInstance] = useState({});

    useEffect(() => {
        const instance = axios.create({
            baseURL: BASE_URL,
            headers: {
                Authorization: initialized ? `Bearer ${keycloak.token}` : undefined,
            },
        });

        setAxiosInstance({instance});

        return () => {
            setAxiosInstance({});
        }
    }, [keycloak, initialized, keycloak.token]);

    return axiosInstance.instance;
};

The error is in the 'Registration' component:错误出现在“注册”组件中:

import {useAxios} from "../utilities/hooks";

const Registration = () => {
    const {initialized} = useKeycloak();
    const axiosInstance = useAxios();
    const [branches, setBranches] = useState({});

    const loadBranches = useCallback(async () => {
        try {
            const response = await axiosInstance.get('/branch');
            setBranches(response.data);
        } catch (error) {
            console.log(`Error when loading branches: ${error.message}`, error);
        }
    }, [axiosInstance]);

    useEffect(() => {
        loadBranches();
    }, [loadBranches]);

...

I first had things working without errors with a similar fetch function, so it seems the axios instance (which is imported) is the culprit.我首先通过类似的fetch function 使事情正常工作,因此似乎 axios 实例(已导入)是罪魁祸首。 I find it also a bit strange that I can not do:我觉得我做不到也有点奇怪:

    useEffect(() => {
        loadBranches();
    }, []);

as then I get React Hook useEffect has a missing dependency: 'loadBranches'. Either include it or remove the dependency array react-hooks/exhaustive-deps overrideMethod @ react_devtools_backend.js:2430 printWarnings @ webpackHotDevClient.js:138 handleWarnings @ webpackHotDevClient.js:143 push../node_modules/react-dev-utils/webpackHotDevClient.js.connection.onmessage @ webpackHotDevClient.js:210然后我得到React Hook useEffect has a missing dependency: 'loadBranches'. Either include it or remove the dependency array react-hooks/exhaustive-deps overrideMethod @ react_devtools_backend.js:2430 printWarnings @ webpackHotDevClient.js:138 handleWarnings @ webpackHotDevClient.js:143 push../node_modules/react-dev-utils/webpackHotDevClient.js.connection.onmessage @ webpackHotDevClient.js:210 React Hook useEffect has a missing dependency: 'loadBranches'. Either include it or remove the dependency array react-hooks/exhaustive-deps overrideMethod @ react_devtools_backend.js:2430 printWarnings @ webpackHotDevClient.js:138 handleWarnings @ webpackHotDevClient.js:143 push../node_modules/react-dev-utils/webpackHotDevClient.js.connection.onmessage @ webpackHotDevClient.js:210

this was not the case when using fetch..., and to simulate a 'when mounted' you'd normally use [].使用 fetch... 时不是这种情况,要模拟“安装时”,您通常会使用 []。

How can I ensure axiosInstance exists at mount?如何确保axiosInstance在挂载时存在?

You can make it simpler:你可以让它更简单:

const Registration = () => {
    const axiosInstance = useAxios();
    const [branches, setBranches] = useState({});

    const loadBranches = useCallback(async () => {
        try {
              const response = await axiosInstance.get('/branch');
              setBranches(response.data);
        } catch (error) {
            console.log(`Error when loading branches: ${error.message}`, error);
        }
    }, [axiosInstance]);

    useEffect(() => {
           axiosInstance && loadBranches(); // <== here
    }, [loadBranches, axiosInstance]);

It will only invoke the loadBranches function when the axiosInstance is defined.它只会在定义 axiosInstance 时调用 loadBranches function。

You need to make it wait till axiosInstance is defined, eg as follows:你需要让它等到axiosInstance被定义,例如如下:

const Registration = () => {
    const axiosInstance = useAxios();
    const [branches, setBranches] = useState({});
    const [axiosReady, setAxiosReady] = useState(false);

    const loadBranches = useCallback(async () => {
        try {
            if (axiosReady) {
                const response = await axiosInstance.get('/branch');
                setBranches(response.data);
            }
        } catch (error) {
            console.log(`Error when loading branches: ${error.message}`, error);
        }
    }, [axiosReady, axiosInstance]);

    useEffect(() => {
        if (axiosInstance) {
            setAxiosReady(true);
        }
    }, [axiosInstance]);

    useEffect(() => {
            loadBranches();
        }, [loadBranches]
    );

...

The component loads fine without the error now and properly triggers axios.该组件现在加载正常,没有错误,并正确触发 axios。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM