本文介绍了React Hooks - 发出Ajax请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始使用React钩子,我想知道AJAX请求应该如何看待?

I have just began playing around with React hooks and am wondering how an AJAX request should look?

我尝试过多次尝试,但我无法将其转换为工作,也不知道实现它的最佳方法。以下是我最近的尝试:

I have tried many attempts, but am unable to get it to work, and also don't really know the best way to implement it. Below is my latest attempt:

import React, { useState, useEffect } from 'react';

const App = () => {
    const URL = 'http://api.com';
    const [data, setData] = useState({});

    useEffect(() => {
        const resp = fetch(URL).then(res => {
          console.log(res)
        });
    });

    return (
        <div>
          // display content here
        </div>
    )
}


推荐答案

您可以创建名为 useFetch 将实现 useEffect 钩子。

You could create a custom hook called useFetch that will implement the useEffect hook.

通过将空数组作为第二个参数传递给 useEffect 钩子将触发<$ c $上的请求c> componentDidMount

By passing an empty array as the second argument to the useEffect hook will trigger the request on componentDidMount.

请参阅下面的代码。

import React, { useState, useEffect } from 'react';

const useFetch = (url) => {
  const [data, updateData] = useState(undefined);

  // empty array as second argument equivalent to componentDidMount
  useEffect(() => {
     fetch(url).then(res => {
        return res.json();
      }).then(json => {
        updateData(json);
     });
  }, []);

  return data;
};

const App = () => {
    const URL = 'http://www.example.json';
    const result = useFetch(URL);

    return (
      <div>
        {JSON.stringify(result)}
      </div>
    );
}

这篇关于React Hooks - 发出Ajax请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 11:11