先来看一张图。
前面所学的redux我们会用了,知道怎么去用redux这个盒子去设置一些共享的 数据和方法让所有组件去使用。但是这些数据是我们本地设置的变量。实际开发中,我们用state去影响ui组件的更新,但是实际上state是来自于服务器响应给我们的,也就是我们发送请求得到的数据。服务器影响state的更新。那么我们这个redux肯定不能保存本地state。也需要去动态的从服务器获取数据。也就是需要数据库中的数据。所有需要用ajax,fetch去和服务器交互。那么RTKQ这个工具就出来了。
1.RTKQ的使用
只是了解这些RTKQ是模糊的,说有什么什么功能也只是说,还是要写出来就知道怎么回事了。
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
const studentsApi = createApi({
reducerPath: 'studentApi',
baseQuery: fetchBaseQuery({
baseUrl: 'http://localhost:1337/api/'
}),
endpoints(build) {
return {
getStudents: build.query({
query() {
return 'students'
}
})
}
}
})
大概就是这样,首先就是引入createApi,然后第一步就是创建Api对象()参数是一个配置对象。里面包含三个参数,我还是自己画一画写一写吧。
第一个参数reducerPath:''是我当前创建api的唯一标识,因为可能有多个api。毕竟数据库有很多表,而且store注册api和reducer都是在store注册的,不能重复。因为默认都是api。
第二个参数是baseQuery:fetchBaseQuery({})指定查询的基本路径,比如我们访问的是http:localhost:1337/api/stuidens可以获取数据,那么我们写到api/就可以了,属性名是baseUrl
第三个参数是endpoints,是一个回调函数,创建完对象RTKQ自动调用这个函数去生成查询方法,就是所谓的封装useFetch了。接收的参数是build,然后需要返回一个对象,对象里面设置请求的具体信息,包含名字,build.query(query表示的是查询方法)({})构建器方法需要一个对象作为参数。然后里面query(){}用这个方法里面指定子路径,以及请求头等请求的具体信息。
写好了就可以去store注册了,比起slice注册多了个中间件,因为自动发起请求,缓存管理错误处理等异步操作都需要中间件作为依赖。
import { configureStore } from "@reduxjs/toolkit";
import studentApi from "./studentApi";
const store = configureStore({
reducer: {
[studentApi.reducerPath]: studentApi.reducer
},
middleware: getDefaultMiddleware =>
getDefaultMiddleware().concat(studentApi.middleware)
})
export default store
/*
计算属性名 (Computed Property Names):
在 JavaScript 对象字面量中,[] 允许你使用表达式作为属性名。
studentApi.reducerPath 是一个动态字符串(例如 'studentApi'),[studentApi.reducerPath] 等价于 'studentApi'。
中间件 (middleware) 是否必须添加?
必须添加,原因如下:
处理异步逻辑:
studentApi 是通过 RTK Query 创建的 API 服务(如 createApi)。它依赖自带的中间件处理数据获取、缓存管理、错误处理等异步操作。
功能依赖:
如果不添加中间件,以下功能将失效:
自动发起网络请求
缓存数据(避免重复请求)
自动生成 pending/fulfilled/rejected 状态
轮询(Polling)、条件查询等高级功能
这里用 concat() 将 RTK Query 中间件合并到默认中间件链中。
*/
注册完之后我们直接引入钩子函数。
import React from 'react'
import { useGetStudentsQuery } from './store/studentApi'
export default function App() {
//调用api查询数据
//钩子函数会返回一个对象作为返回值 请求过程中的相关数据都在该对象中存储
const { data, isSuccess, isLoading } = useGetStudentsQuery()//调用api中的钩子查询数据
console.log('data', data)
return (
<div>
{isLoading && <p>数据加载中</p>}
{isSuccess && data.data.map((item) =>
<p key={item.id}>
{item.name}---{item.address}--{item.age}---{item.gender}
</p>
)}
</div>
)
}
对象解构拿取出来需要的数据,这里我们可以看出isLoading,isSuccess都帮我们添加到了返回的对象中保存。调用这个钩子之后。到这里RTKQ的使用就完成了。
2.列表的增删改查
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
const studentApi = createApi({
reducerPath: 'studentApi',
baseQuery: fetchBaseQuery({
baseUrl: 'http://localhost:1337/api/'
}),
tagTypes: ['student'],//用来指定api类型,
endpoints(build) {
return {
getStudents: build.query({
query() {
return 'students'
},
transformResponse(baseQueryReturnValue) {
//用来转换响应数据的格式
console.log('baseQueryReturnValue', baseQueryReturnValue)
return baseQueryReturnValue.data
},
keepUnusedDataFor: 0,//设置缓存的时间
providesTags: ['student']
}),
getStudentsById: build.query({
query(id) {
return students/${id}
},
keepUnusedDataFor: 5//设置缓存的时间单位是秒默认 是60s
}),
delStudent: build.mutation({
query(id) {
return {
url: students/${id},
method: 'delete'
}
}
}),
addStudent: build.mutation({
query(stu) {
return {
url: 'students',
method: 'post',
body: { data: stu },
headers: {
"Content-type": "application/json"
}
}
},
invalidatesTags: ['student']
//使对应标签的请求失效重新刷新
}),
updataStudent: build.mutation({
query(stu) {
return {
url: students/${stu.id},
method: 'put',
body: {
data: stu.attributes
},
headers: {
"Content-type": "application/json"
}
}
},
invalidatesTags: ['student']
})
}
}
})
export const {
useGetStudentsQuery,
useGetStudentsByIdQuery,
useDelStudentMutation,
useAddStudentMutation,
useUpdataStudentMutation
} = studentApi
export default studentApi
import React, { useEffect } from 'react'
import './StudentForm.css'
import { useAddStudentMutation, useGetStudentsByIdQuery, useUpdataStudentMutation } from '../store/studentApi'
export default function StudentForm(props) {
const { data, isSuccess } = useGetStudentsByIdQuery(props.stuId, {
skip: !props.stuId
})
const [input, setInput] = React.useState({
name: '',
age: '',
address: '',
gender: '男'
})
const [addStudent, { isSuccess: isAddSuccess }] = useAddStudentMutation()
const [updataStudent, { isSuccess: isUpdataSuccess }] = useUpdataStudentMutation()
console.log('props.stuId', props.stuId)
useEffect(() => {
if (isSuccess) {
setInput(data.data)
}
}, [isSuccess])
//studentForm一加载就需要加载最新的学生数据
const nameChange = (e) => {
setInput((preState) => ({ ...preState, name: e.target.value }))
}
const ageChange = (e) => {
setInput((preState) => ({ ...preState, age: +e.target.value }))
}
const genderChange = (e) => {
setInput((preState) => ({ ...preState, gender: e.target.value }))
}
const addressChange = (e) => {
setInput((preState) => ({ ...preState, address: e.target.value }))
}
const handle = () => {
addStudent(input)
}
const updataHandle = () => {
updataStudent({
id: props.stuId,
attributes: {
name: input.name,
age: input.age,
gender: input.gender,
address: input.address
}
})
props.onCancel()
}
return (
<>
<tr className='student-form'>
<td><input type="text" onChange={nameChange} value={input.name} /></td>
<td><select name="" id="" onChange={genderChange} value={input.gender}>
<option value="男">男</option>
<option value="女">女</option>
</select></td>
<td><input type="text" onChange={ageChange} value={input.age} /></td>
<td><input type="text" onChange={addressChange} value={input.address} /></td>
<td>
{props.stu && <><button onClick={() => { props.onCancel() }}>取消</button><button onClick={updataHandle}>修改</button></>}
{!props.stu && <button onClick={handle}>添加</button>}
</td>
</tr>
{/* {loading && <tr><td colSpan={5}>添加中</td></tr>}
{error && <tr><td colSpan={5}>添加失败</td></tr>} */}
</>
)
}
出来get请求,其他的请求都需要用mutation去创建,然后return{}写明method以及body,如果 。
注意body:{data:stu}需要用data属性值作为参数传。其他的就没什么。 直接在组件里面引入钩子调用。需要id的传id,以及数据传过去就好了。
剩下的一些比如像ProbiderTags:['student']以及invalidataesTags:[students]提供的标签,可以删除对应标签的缓存然后重新触发对应的请求。
reduxApi大概就这些吧。至少整个流程是通了一遍了。对于基础使用应该是够了。项目实战的时候在练习吧。