react Fetch 请求 举个栗子

fetch 关注分离设计思想

import React, { Component } from 'react'

export default class Search extends Component {
    // 起步版
	search =  () => {
		const id = 1;
		fetch(`/api/search/getdata?id=${{id}`)
		.then(
			response =>{
				// 跟服务器联系上了 
				return response.json()
			},
			error => {
				// 我跟服务器玩不上了 
				return new Promise(()=>{})
				console.log(error)
			}
		)
		.then(
			response =>{
				// 成功的获取到了数据
				console.log(response)
			},
			error => {
				console.log(error)
			}
		)
	}
	// 优化版
	search = async  ()=> {
		try {
			const id = 1;
			const res = await fetch(`/api/search/getdata?id=${{id}`)
			const data = await res.json()
		} catch (erro) {
			conslose.log(erro)
		}
		
	}

	render() {
		return (
			<section className="jumbotron">
				<div>
					<button onClick={this.search}>搜索</button>
				</div>
			</section>
		)
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
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> ); ``` 通过以上步骤,我们可以使用React中的fetch方法来发送分页数据请求,并且在页面展示和处理分页操作。当点击下一页按钮时,会发送新的fetch请求来获取下一页的数据,并更新页面的展示。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值