react+redux异步操作数据

react+redux异步操作数据

redux中操作异步方法,主要是: 1、借助createAsyncThunk()封装异步方法;2、通过extraReducers处理异步方法触发后的具体逻辑,操作派生的state

1、异步操作的slice

import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'

// 使用该类型定义初始 state
const initialState = {
  systemName: '三分之一'
}
// promise封装的定时器
function delay(ms: number, data: string) {
  return new Promise((resolve) => setTimeout(() => resolve(data), ms))
}
// AsyncThunk<void, void, AsyncThunkConfig>
// createAsyncThunk<string, string, object> :
// 第一个string: 'system/updateSystemName'
// 第二个string: updateSystemName调用时,传的参数
// object: AsyncThunkConfig 配置对象
// 详细可见 : https://redux-toolkit.js.org/usage/usage-with-typescript#createasyncthunk
export const updateSystemName = createAsyncThunk<string, string>(
  'system/updateSystemName',
  async (data, config): Promise<string> => {
    console.log(data, config)
    const res = await delay(2000, data)
    return res as string
  }
)

const systemSlice = createSlice({
  name: 'system',
  initialState,
  reducers: {},
  extraReducers: (builder) => {
    // 触发updateSystemName,执行builder.addCase的回调
    builder.addCase(updateSystemName.fulfilled, (state, action) => {
      // action: {
      //   type: 'system/updateSystemName/fulfilled'
      // },
      // payload: dispatch(updateSystemName('单点的')) updateSystemName
      // meat: {arg: '单点的', ...}
      state.systemName = action.payload
    })
  }
})
export default systemSlice.reducer

AsyncThunkConfig 如图所示:
在这里插入图片描述

2、组件中调用异步的方法

import { updateSystemName } from '@/store/reducers/systemSlice'
import { RootState } from '@/store'
import { useAppDispatch } from '@/hooks/useAppDispatch'
import { useAppSelector } from '@/hooks/useAppSelector'

const Home = () => {
  const { systemName } = useAppSelector(
    (state: RootState) => state.systemReducer
  )
  const dispatch = useAppDispatch()
  const test = () => {
    // useDispatch() 返回值函数默认期望的参数类型是 AnyAction
    // 异步处理是updateSystemName: AsyncThunkAction
    // 所以这块使用官网推荐的自定义封装的hooks: useAppDispatch
    dispatch(updateSystemName('单点的'))
  }
  return (
    <>
      <div>home page</div>
      <p>{systemName}</p>
      <button onClick={test}>测试</button>
    </>
  )
}

export default Home

4、给dispatch()参数添加Action类型

解决: 类型“AsyncThunkAction<string, string, AsyncThunkConfig>”的参数不能赋给类型“AnyAction”的参数。

  1. useAppDispatch
import type { AppDispatch } from '@/store'
import { useDispatch } from 'react-redux'

// 给useDispatch 添加泛型, 默认接收的参数是AnyAction
// import {  useDispatch } from 'react-redux'
export const useAppDispatch = () => useDispatch<AppDispatch>()
  1. useAppSelector
import type { RootState } from '@/store'
import { TypedUseSelectorHook, useSelector } from 'react-redux'

// import { useSelector } from 'react-redux'
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector
  1. store中
    export type RootState = ReturnType<typeof store.getState>
    export type AppDispatch = typeof store.dispatch
import { configureStore } from '@reduxjs/toolkit'
import { combineReducers } from 'redux'
// 数据持久化
import { persistStore, persistReducer } from 'redux-persist'
import storageLocation from 'redux-persist/lib/storage' // defaults to localStorage for web    // redux-persist/lib/storage/session
// reducers
import userReducer from './reducers/userSlice'
import systemReducer from './reducers/systemSlice'
const persistConfig = {
  key: 'root',
  storage: storageLocation
}
// 持久化reducers
const persistedReducer = persistReducer(
  persistConfig,
  combineReducers({
    //数据切片
    userReducer,
    systemReducer
  })
)

const store = configureStore({
  // userReducer 模块名
  reducer: persistedReducer,
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware({
      serializableCheck: false
    })
})

// 可以订阅 store
// store.subscribe(() => console.log(store.getState(), 'userSlice'))

// 持久化的store
const persistor = persistStore(store)

export { store, persistor }

// Infer the `RootState` and `AppDispatch` types from the store itself
export type RootState = ReturnType<typeof store.getState>
// Inferred type: {posts: PostsState, comments: CommentsState, users: UsersState}
export type AppDispatch = typeof store.dispatch
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
前端开发中的React Redux全家桶是一套常用的技术栈,用于构建复杂的Web应用程序。React是一个由Facebook开发的JavaScript库,用于构建用户界面。它通过将应用程序拆分成可重用的组件,使开发人员能够更轻松地开发、测试和维护Web应用程序。 Redux是一个用于管理应用程序状态的库。它采用了一种称为单一状态树的模式,将整个应用程序的状态存储在一个对象中,并使用纯粹的函数来修改状态。Redux的核心概念包括:store、reducer和action。Store是应用程序的状态容器,reducer是一个纯函数,用于根据action来修改状态,而action代表用户触发的操作React Redux是将ReactRedux结合在一起使用的库。通过使用React Redux,我们可以将Redux的状态管理功能集成到React组件中。React Redux提供了一种称为容器组件的机制,它负责从Redux store中提取数据,并将其作为props传递给展示组件。这种分离开发的模式使得代码更加模块化和易于维护。 React Redux全家桶还包括一些其他的辅助库,如React Router用于跟踪和管理应用程序的URL路径,以及Redux Thunk或Redux Saga用于处理异步操作。这些库的整合和使用能够帮助开发人员构建可扩展、高效和易于维护的前端应用程序。 总之,前端开发中的React Redux全家桶提供了一套完善的工具和库,帮助开发人员构建复杂的Web应用程序。它能够将状态管理和用户界面开发结合在一起,并提供了一种模块化和分离开发的解决方案。通过学习和使用React Redux全家桶,开发人员可以提高开发效率,并构建出更好的用户体验。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

原谅我很悲

不要打赏哦,加个好友一起学习呗

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值