一、概述
@reduxjs/toolkit和react-redux是用于在React应用中管理全局状态的工具库
1、@reduxjs/toolkit:
@reduxjs/toolkit是Redux官方推荐的工具库,是对Redux的二次封装,它提供了一些便捷的API和工具,帮助开发者更快速地编写Redux代码。@reduxjs/toolkit包含了一些核心概念,如createSlice用于创建Reducer和Action,configureStore用于创建Reduxstore等- 使用
@reduxjs/toolkit可以减少样板代码,提高开发效率,并且有助于遵循Redux最佳实践 - 官方文档:https://redux-toolkit.js.org/
2、react-redux:
react-redux是Redux官方提供的React绑定库,它提供了一些React Hooks和组件,用于在React组件中访问Redux store和派发Action。- 通过
react-redux,我们可以将Redux store中的状态映射到React组件的props中,以及将派发Action的方法传递给React组件。 - 使用
react-redux可以方便地在React应用中集成Redux,其中的Provider组件将Redux Store与React应用连接起来 。 - 官方文档:https://cn.redux.js.org/introduction/why-rtk-is-redux-today
二、配置与使用
1、安装
npm i @reduxjs/toolkit react-redux
2、创建一个stroe文件,其中在创建如下:
(1)modules文件存储子store模块
(2)index.js组合modules中所有子模块,并导出store
文件创建参照下图:

3、在modules文件下创建 userStore.ts(这是我的演示demo,名字可自定义, 使用@reduxjs/toolkit创建切片,如下:
import { createSlice } from '@reduxjs/toolkit'const userSlice = createSlice({name: 'user',initialState: {isLogin: false,info: {},list: []},reducers: {setInfo(state, action) {state.info = action.payload},setIsLogin(state, action) {state.isLogin = action.payload},setList(state, action) {state.list = action.payload}}
})
//异步请求方法
const getList = () => {return async (dispatch: (arg0: any) => void) => {const res = await axios.get('接口地址')dispatch(getList(res.data.list))}
}
export const { setInfo, setIsLogin,getList } = userSlice.actions
export default userSlice.reducer
4、在stroe文件下的index.ts中组合modules中的所有切片,导出store
import { configureStore } from '@reduxjs/toolkit'
import user from './modules/userStore'
export const store = configureStore({reducer:{user,}
})
5、 Provider组件将Redux Store与React应用连接起来 。
import React from 'react'
import ReactDOM from 'react-dom/client'
import './index.css'
import App from './App'
import reportWebVitals from './reportWebVitals'
import { Provider } from 'react-redux'
import { store } from './store'const root = ReactDOM.createRoot(document.getElementById('root') as HTMLElement)
root.render(<React.StrictMode><Provider store={store}><App /></Provider></React.StrictMode>
)// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals// reportWebVitals()
reportWebVitals(console.log)
主要代码看配图:

6、使用useSelector、 useDispatch钩子函数 获取state 和 修改state
import React from 'react'
import { store } from '@/store'
import { useSelector, useDispatch } from 'react-redux'
import { setIsLogin } from './store/modules/userStore'
type getStateFunType = typeof store.getState
type IRootState = ReturnType<getStateFunType>
function App() {// let state = useSelector((state: IRootState) => ({// info: state.user.info,// isLogin: state.user.isLogin,// }))let {isLogin} = useSelector((state: IRootState)=>state.user)let dispatch = useDispatch()let login = () => {dispatch(setIsLogin(true))}return (<div className="App"><div>{isLogin ? '吾乃法外狂徒张三' : '来者何人报上名来'}</div>{!isLogin && <button onClick={login}> 报山头 </button>}</div>)
}
主要代码看配图:
