react 调用api实现数据列表的渲染
作者:互联网
首先建一个项目 (vite构建)
yarn create vite Topics-Date --template react
封装axios
npm i axios //在该文件夹下下载zxios
新建utils/request.js
import axios from 'axios'
const instance = axios.create({
baseURL:"https://cnodejs.org/api/v1"
})
export default instance
新建 src/api/Topics.js 设置请求api
import axios from 'axios'
const instance = axios.create({
baseURL:"https://cnodejs.org/api/v1"
})
export default instance
新建component/TopicsList.jsx 对页面进行编写
import {useEffect,useState} from 'react'
import { GET_TOPICS } from '../api/Topics'
export default function TopicsList() {
const [topics,setTopics] = useState([])
const [page,setPage] = useState(1)
const [limit,setLimit] = useState(10)
//创建一个请求函数
const getTopic = async (params) =>{
const res = await GET_TOPICS(params)
setTopics(res.data.data)
}
//请求函数
useEffect(()=>{
getTopic({page,limit})
},[page,limit])
return (
<div>
{
topics.map(topic => <div key={topic.id}>{topic.title}</div>)
}
<button onClick={()=> setPage(page-1)} disabled={page==1}>上一页</button>
<button onClick={()=> setPage(page+1)} disabled={page==topics.length-1}>下一页</button>
<select value = {limit} onChange={(e)=> setLimit(+e.target.value)}>
<option value="10">10</option>
<option value="20">20</option>
<option value="30">30</option>
<option value="40">40</option>
</select>
</div>
)
}
在App.jsx 中引入列表组件
import { useState } from 'react'
import TopicsList from './component/TopicsList'
function App() {
const [status, setStatus] = useState(true)
if(status){
return (
<div className="App">
<TopicsList></TopicsList>
</div>
)
}
return (
<div className="App">
</div>
)
}
export default App
可实现对数据的渲染 以及上一页下一页的转化 以及显示几条的设置
如图效果
标签:axios,const,渲染,react,api,useState,import,page 来源: https://blog.csdn.net/weixin_48864616/article/details/123098228