前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >React技巧之发出http请求

React技巧之发出http请求

作者头像
chuckQu
发布2022-08-19 16:06:35
6930
发布2022-08-19 16:06:35
举报
文章被收录于专栏:前端F2E

原文链接:https://bobbyhadz.com/blog/react-send-request-on-click[1]

作者:Borislav Hadzhiev[2]

正文从这开始~

总览

在React中,通过点击事件发出http请求:

  1. 在元素上设置onClick属性。
  2. 每当元素被点击时,发出http请求。
  3. 更新state变量,并重新渲染数据。

如果你使用axios,请向下滚动到下一个代码片段。

代码语言:javascript
复制
import {useState} from 'react';

const App = () => {
  const [data, setData] = useState();
  const [isLoading, setIsLoading] = useState(false);
  const [err, setErr] = useState('');

  const handleClick = async () => {
    setIsLoading(true);
    try {
      const response = await fetch('<https://reqres.in/api/users>', {
        method: 'POST',
        body: JSON.stringify({
          name: 'John Smith',
          job: 'manager',
        }),
        headers: {
          'Content-Type': 'application/json',
          Accept: 'application/json',
        },
      });

      if (!response.ok) {
        throw new Error(`Error! status: ${response.status}`);
      }

      const result = await response.json();

      console.log('result is: ', JSON.stringify(result, null, 4));

      setData(result);
    } catch (err) {
      setErr(err.message);
    } finally {
      setIsLoading(false);
    }
  };

  console.log(data);

  return (
    <div>
      {err && <h2>{err}</h2>}

      <button onClick={handleClick}>Make request</button>

      {isLoading && <h2>Loading...</h2>}

      {data && (
        <div>
          <h2>Name: {data.name}</h2>
          <h2>Job: {data.job}</h2>
        </div>
      )}
    </div>
  );
};

export default App;

react-make-request-on-click.gif

fetch

上述示例向我们展示了,在React中,如何通过点击按钮发送HTTP POST 请求。

我们在button元素上设置了onClick属性,因此每当按钮被点击时,handleClick函数将会被调用。我们通过async关键字标记了handleClick函数,因此我们可以使用await关键字来等待内部的Promise返回。

handleClick函数中,我们等待POST请求的完成并更新state变量。

该示例使用了原生的 fetch API,但如果你使用axios依赖包,这个概念也适用。

axios

下面是如何使用axios包在点击按钮时发出http POST请求。

如果你决定使用axios,请确保你已经通过运行npm install axios安装了该软件包。

代码语言:javascript
复制
import {useState} from 'react';
import axios from 'axios';

const App = () => {
  const [data, setData] = useState();
  const [isLoading, setIsLoading] = useState(false);
  const [err, setErr] = useState('');

  const handleClick = async () => {
    setIsLoading(true);
    try {
      const {data} = await axios.post(
        '<https://reqres.in/api/users>',
        {name: 'John Smith', job: 'manager'},
        {
          headers: {
            'Content-Type': 'application/json',
            Accept: 'application/json',
          },
        },
      );

      console.log(JSON.stringify(data, null, 4));

      setData(data);
    } catch (err) {
      setErr(err.message);
    } finally {
      setIsLoading(false);
    }
  };

  console.log(data);

  return (
    <div>
      {err && <h2>{err}</h2>}

      <button onClick={handleClick}>Make request</button>

      {isLoading && <h2>Loading...</h2>}

      {data && (
        <div>
          <h2>Name: {data.name}</h2>
          <h2>Job: {data.job}</h2>
        </div>
      )}
    </div>
  );
};

export default App;

react-make-request-on-click.gif

上述示例向我们展示了,如何使用axios在点击按钮时,发出http POST 请求。

如果你使用axios,请确保你已经在项目的根目录下运行npm install axios来安装该包。

使用axios包时的语法更简洁一些,我们要处理的实现细节也更少,但概念是一样的。

我们必须在一个按钮元素上设置onClick属性,并在每次点击按钮时发出一个HTTP请求。

参考资料

[1]

https://bobbyhadz.com/blog/react-send-request-on-click: https://bobbyhadz.com/blog/react-send-request-on-click

[2]

Borislav Hadzhiev: https://bobbyhadz.com/about

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2022-06-25,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 前端F2E 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 总览
  • fetch
  • axios
    • 参考资料
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档