useEffect挂钩中的未定义变量

时间:2020-08-25 22:26:01

标签: reactjs react-hooks keycloak

使用@react-keycloak/web库,我试图在组件加载时获取后端API数据。我已经尝试通过使用useCallback按下页面上的按钮来获取所需的数据,但是,当我在useEffect中执行相同的操作时,这部分工作正常,我遇到了未定义的错误。让我们看一下代码(它也可以在底部作为代码段使用):

code1

我得到的错误是:

TypeError: Cannot read property 'get' of undefined
(anonymous function)
.../ListPage.js:19
  16 | 
  17 |    // This way it doesn't
  18 |    useEffect(() => {
> 19 |      axiosInstance.get('/resolutions').then(response => {
  20 | ^       setResolutions(response.data)
  21 |      })
  22 |    }, [axiosInstance])

我不确定我在做什么错。 useEffectuseCallback之间的区别是什么使得它们中的第一个抛出错误而第二个却正常工作?


hooks.js:

import { useState, useEffect } from 'react'
import axios from 'axios'

import { useKeycloak } from '@react-keycloak/web'

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

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

    setAxiosInstance({ instance })

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

  return axiosInstance.instance
}

ListPage.js:

import React, { useEffect, useCallback, useState } from 'react'
import { useKeycloak } from '@react-keycloak/web'
import { useAxios } from '../utils/hooks'

export default () => {
const [modifyResolutions, setResolutions] = useState([])
const axiosInstance = useAxios('http://localhost:8080')

// This doesn't
useEffect(() => {
  axiosInstance.get('/resolutions').then(response => {
    setResolutions(response.data)
  })
}, [axiosInstance])

// This works
const callApi = useCallback(() => {
  axiosInstance.get('/resolutions').then(response => {
    setResolutions(response.data)
  })
}, [axiosInstance])

return ( 
  <div>
    <div>
        {modifyResolutions.map(x => <h2>{x.text}</h2>)}
    </div>
    <button type="button" onClick={callApi}>
    Call API
  </button>
  </div>
 );
}

0 个答案:

没有答案