【react】react18的学习(七)--redux-toolkit

上一篇:react18的学习(六)–redux中间件

替代原生redux创建store,简化store的创建;

与react-redux:前者是简化store的创建;后置是简化store的使用,且针对redux、redux-toolkit的store均有封装;

特点:

  • configureStore({})创建store
  • 内置了一些中间件,如redux-thunk
  • 基于切片机制createSlice:将每个模块的reducer与action合成到一个切片中
  • 对应react-redux在组件中的使用也发生改变,connect方式也能用,多了手动派发方式;

具体步骤:

  • 第一步:创建各模块切片:src\store\features\taskSlice.js
import { createSlice } from '@reduxjs/toolkit'
import { getTaskList } from '../../api'

const taskSlice = createSlice({
  name: 'task',
  initialState: {
    taskList: null,
  },
  reducers: {
    // 不需要返回值,因为这里的所有代码要被整合成一个reducer,统一返回state
    queryAll(state, action) {
      state.taskList = action.payload
    },
    ...
  },
})
// console.log(taskSlice):
// actions: {queryAll: ƒ, completeById: ƒ, deleteById: ƒ}
// caseReducers: {queryAll: ƒ, completeById: ƒ, deleteById: ƒ}
// getInitialState: ƒ ()
// name: "task"
// reducer: ƒ (state, action)

// 手动导出action方法,返回值为{type:**, {payload:[传的值]}}
export const { queryAll, completeById, deleteById } = taskSlice.actions
// 异步action方法:使用redux-toolkit内置的redux-thunk中间件
export const queryAllAsync = () => {
  return async dispatch => {
    let list = []
    try {
      let res = await getTaskList({ state: 0 })
      if (+res.code === 200) {
        list = res.data
      }
    } catch (_) {}
    dispatch(queryAll(list))
  }
}
// 默认导出reducer
export default taskSlice.reducer

  • 第二步:创建store:src\store\index.js
import { configureStore } from '@reduxjs/toolkit'
import logger from 'redux-logger'
// import promise from 'redux-promise'
import thunk from 'redux-thunk'
import taskSliceReducer from './features/taskSlice'

const store = configureStore({
  reducer: {
    task: taskSliceReducer,
  },
  middleware: [logger, thunk],
})

export default store
  • 第三步:根组件导入store,写法不变
import { Provider } from 'react-redux'
import store from './store'
root.render(
  <ConfigProvider locale={zhCN}>
    <Provider store={store}>
      <Task></Task>
    </Provider>
  </ConfigProvider>
)
  • 第四步:子组件中使用,connect方式也能用,这里用hooks,手动派发
// 操作store
import {
  queryAllAsync,
  completeById,
  deleteById,
} from '../../redux-toolkit-store/features/taskSlice'
import { useSelector, useDispatch } from 'react-redux'

// 获取state状态和派发
  let { taskList } = useSelector(state => state.task),
    dispatch = useDispatch()

  // 首次挂载后
  useEffect(() => {
    dispatch(queryAllAsync())
  }, [])
  // 两种更新途径:派发后taskList改变更新组件、useState状态改变更新组件
  useEffect(() => {
    if (!taskList) {
      setDataSource([])
      return
    }
    if (selectedIndex != 0) {
      taskList = taskList.filter(item => item.state == selectedIndex)
    }
    setDataSource(taskList)
    setTableLoading(false)
  }, [taskList, selectedIndex])

你可能感兴趣的:(react,react.js,学习,javascript)