react-fetch数据发送请求

在一个项目中,数据的请求发送数据是最为重要的,不可能我们的数据都是自己进行编写的

在react中官方推荐使用的方法是fetch。当然它里面也可以使用vue中的axios请求数据,jQuery的$.ajax 以及元素ajax

下面重点说一下fetch

get方法非常简单,

1 componentDidMount() {
2         fetch('http://127.0.0.1:8100/getAaa')
3             .then(res=>res.json())
4             .then(json=>this.setState({list: json}))
5 }

post方法相对于get有点复杂,

 1 add() {
 2         fetch('http://127.0.0.1:8100/getDel',{
 3             method:'post',//改成post
 4             mode: 'cors',//跨域
 5             headers: {//请求头
 6                 'Content-Type': 'application/x-www-form-urlencoded'
 7             },
 8             body:"..."//向服务器发送的数据
 9         })
10             .then(res=>res.json())
11             .then(json=>{console.log(json)})
12 }

以上就是关于react fetch两种使用方法

有什么不足的或者不对的欢迎大家指出

转载于:https://www.cnblogs.com/nixu/p/9523314.html

React是一种流行的JavaScript库,用于构建用户界面。fetch()是它提供的一种用于发送网络请求的方法,常用于获取数据。 在React使用fetch请求分页数据的步骤如下: 1. 需要使用一个状态变量来存储分页数据,例如: ```jsx const [data, setData] = useState([]); ``` 2. 创建一个函数来发送fetch请求获取数据,例如: ```jsx const fetchData = async () => { try { const response = await fetch('http://api.example.com/data?page=1'); // 发送GET请求 const json = await response.json(); setData(json.data); // 将获取的数据存储到状态变量 } catch (error) { console.log(error); } } ``` 3. 在组件加载后调用fetchData函数来获取初始数据,可以使用useEffect钩子来实现: ```jsx useEffect(() => { fetchData(); }, []); ``` 4. 创建一个函数来处理分页操作,例如: ```jsx const handlePagination = async (page) => { try { const response = await fetch(`http://api.example.com/data?page=${page}`); const json = await response.json(); setData(json.data); // 更新分页数据 } catch (error) { console.log(error); } } ``` 5. 在组件展示分页按钮,并调用handlePagination函数来处理分页操作,例如: ```jsx return ( <div> {data.map(item => <div key={item.id}>{item.name}</div>)} <button onClick={() => handlePagination(2)}>下一页</button> </div> ); ``` 通过以上步骤,我们可以使用Reactfetch方法来发送分页数据请求,并且在页面展示和处理分页操作。当点击下一页按钮时,会发送新的fetch请求来获取下一页的数据,并更新页面的展示。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值