简体   繁体   English

React 中的 Axios 用于存储响应以备将来使用

[英]Axios in React for storing response for future use

I'm trying to use the response returned by an Axios GET request for displaying it on my webpage.我正在尝试使用 Axios GET 请求返回的响应在我的网页上显示它。 However, when I'm trying to store the response using the useState hook in a state variable, I'm not getting the API fetched data in my state variable.但是,当我尝试使用 useState 挂钩将响应存储在 state 变量中时,我没有在我的 state 变量中获取 API 获取的数据。

I figure it has something to do with the async nature of Axios. Any help on how I can successfully store it in the state would greatly help.我认为这与 Axios 的异步性质有关。任何有关如何成功将其存储在 state 中的帮助都会大有帮助。 Thanks.谢谢。

const [responseData, setResponseData] = useState('');

axios.get('/URL', {
   params: {
        ABC: 'abc',
        XYZ: '150'
    }
})
.then((response) => {
  console.log(response);
  setResponseData(response.data);
}, (error) => {
  console.log(error);
})

console.log('ResponseData: ' + responseData);

Infinite loop -> so call with UseEffect无限循环 -> 所以用 UseEffect 调用

The problem with the code is that when setResponseData update the response, the whole component rerender and that's make axios call again and again.代码的问题在于,当setResponseData更新响应时,整个组件重新呈现,这使得axios一次又一次地调用。

My solution is call with useEffect.我的解决方案是调用 useEffect。

export default function App() {

  const [responseData, setResponseData] = React.useState('');

  React.useEffect(() => {
    (async function () {
      await axios.get('https://cat-fact.herokuapp.com/facts', {
        params: { ABC: 'abc', XYZ: '150' }
      }).then((response) => {
        setResponseData({ response: response.data, check: Date.now() });
      }, (error) => {
        console.log(error);
      })
    })();
  }, [])

  console.log('ResponseData:', responseData);

  return (
    <div className="App">
      <span>lalla</span>
    </div>
  );
}

So now we get empty in the initial render and after fetch we get the data:)所以现在我们在初始渲染中得到空,在获取之后我们得到数据:)

在此处输入图像描述

If you want to fetch data in a component then the best way to properly do this is via useEffect hook:如果您想在组件中获取数据,那么正确执行此操作的最佳方法是通过useEffect挂钩:

const [responseData, setResponseData] = useState('');

useEffect(() => {
    const fetchData = async () => {
        try {
            const { data } = await axios.get('/URL', {
               params: {
                    ABC: 'abc',
                    XYZ: '150'
               }
            });
            setResponseData(data);
        } catch (error) {
            console.log(error);
        }
    }
    fetchData();
}, []); // with no dependencies, this hook will run only on component mount

// Hook below serves only to confirm when data lands in your responseData state
useEffect(() => {
    if (responseData) console.log('ResponseData: ' + responseData);
}, [ responseData ]);

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

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