当前位置: 首页 > wzjs >正文

企业网站的建设电话咨询西乡专业做网站公司

企业网站的建设电话咨询,西乡专业做网站公司,电商设计招聘,邯郸做网站服务商先来看一张图。前面所学的redux我们会用了,知道怎么去用redux这个盒子去设置一些共享的 数据和方法让所有组件去使用。但是这些数据是我们本地设置的变量。实际开发中,我们用state去影响ui组件的更新,但是实际上state是来自于服务器响应给我们…

        先来看一张图。

        

        前面所学的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大概就这些吧。至少整个流程是通了一遍了。对于基础使用应该是够了。项目实战的时候在练习吧。

        

http://www.dtcms.com/wzjs/575025.html

相关文章:

  • 网站域名放国外宁波建设网网点
  • 蓝顿长沙网站制作公司国内永久免费建站
  • 网站建设胶州广西南宁市网站制作公司
  • 安远网站建设网站开发怎么入账
  • 潍坊制作网站公司兴义网站开发公司
  • 学做电商需要什么条件搜索引擎优化关键词
  • 网站做百度竞价的标志沈阳电商网站建设
  • seo网站建设视频建设网站一般多钱
  • 网站基础风格创建网站建设1000zhu
  • 江苏省网站建设与管理历年自考试题代理注册公司条件
  • 怎么做百度提交入口网站聊天软件开发需要多少钱
  • 用网站做淘客怎么赚钱广告优化师的职业规划
  • 大连网站建设公司哪家好小红书营销
  • 宁波网站排名优化社交网站建设码
  • 24手表网站空包网站分站怎么做
  • 深圳高端营销网站模板苏州网站建设最佳方案
  • 深圳网站建设工资手机网站的内容模块
  • 网站不交换友情链接可以吗邢台建设企业网站
  • 网站开发工程师要考什么证湛江商城网站开发设计
  • 搜索引擎网站建设公司企业网站的布局类型
  • 网站建设服务天软科技专业俄文网站建设
  • 高中网站制作中国建设人才网服务信息网
  • 网站开发离线下载报表wordpress看流量
  • 还有哪些网站可以做淘宝活动吗昆山建设局网站表格下
  • 春蕾科技 网站建设网站建设苏州公司
  • 规划建立一个网站竞价推广开户公司
  • 咸宁网站设计公司怎么创建网站与网页
  • 用在线网站做的简历可以吗从58做网站怎么做
  • 中国建设银行章丘支行网站广东培训seo
  • 物流网站的建设论文唐山企业网站