如何在 reactjs 中使用 axios
介绍
axios 是一个流行的库,用于执行 get、post、put、delete 等 http 请求。 axios 非常适合在 react 应用程序中使用,因为它提供简单的语法并支持 promises。本文将讨论如何在 reactjs 应用程序中使用 axios。
axios 安装
确保你的 react 项目中安装了 axios:
npm install axios
登录后复制
在 react 组件中使用 axios
例如,我们希望使用 get 方法从 api 检索数据并将其显示在 react 组件中。
获取请求:
import react, { useeffect, usestate } from 'react';import axios from 'axios';const app = () => { const [data, setdata] = usestate([]); const [loading, setloading] = usestate(true); const [error, seterror] = usestate(null); useeffect(() => { const fetchdata = async () => { try { const response = await axios.get('https://jsonplaceholder.typicode.com/posts'); setdata(response.data); setloading(false); } catch (error) { seterror(error); setloading(false); } }; fetchdata(); }, []); if (loading) returnloading...
; if (error) returnerror: {error.message}
; return ();};export default app;posts
{data.map((post) => (
- {post.title}
))}
登录后复制
说明:
在组件首次加载时使用useeffect调用fetchdata函数。axios.get 用于从 api url 检索数据。状态数据、加载和错误用于存储检索到的数据、加载状态和错误。post 请求: 要向服务器发送数据,可以使用post方法,如下所示:
import React, { useState } from 'react';import axios from 'axios';const App = () => { const [title, setTitle] = useState(''); const [body, setBody] = useState(''); const handleSubmit = async (e) => { e.preventDefault(); try { const response = await axios.post('https://jsonplaceholder.typicode.com/posts', { title, body, }); console.log('Response:', response.data); alert('Post successfully created!'); } catch (error) { console.error('Error posting data:', error); } }; return ();};export default App;Create a Post
setTitle(e.target.value)} />
登录后复制
说明:
axios.post 方法用于将标题和正文数据发送到 api。handlesubmit 函数处理表单提交并将数据发送到服务器。
以上就是如何在 ReactJS 中使用 Axios – GET 和 POST 请求的详细内容,更多请关注【创想鸟】其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。
发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2664464.html