本文最后更新于:2024年4月25日 上午
React Redux Toolkit
是对redux
封装,使其使用更加方便
安装
1
| pnpm i react-redux @reduxjs/toolkit
|
创建state模块
createSlice
方法类似于创建一个state的小模块,该方法接收一个对象,
- 该对象的
name
属性用于创建actionstype
前缀,应为唯一的值
initialState
属性为初始state
reducers
属性为操作该state的方法集
src/redux/modules/userSlice.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| import { createSlice } from '@reduxjs/toolkit'
const userSlice = createSlice({ name: 'user', initialState: { name: 'Jonathan', admin: true, token: '1234567890', }, reducers: { logout: (state) => { state.name = '' state.admin = false state.token = '' },
login: (state, action) => { console.log(action.type)
state.name = action.payload.name state.admin = action.payload.admin state.token = action.payload.token }, }, })
export const { logout, login } = userSlice.actions
export default userSlice.reducer
|
reducers
中的方法接收两个参数
state
: 该切片的state,修改属性无需拷贝,直接修改(state使用proxy
)
action: {type: String, paylaod}
: type
为${name}/${方法名}
的字符串,payload
为使用方法时传入的参数.
挂载模块
reducer
的属性名为模块名,读取state
时用以区分不同的state
模块
src/redux/index.js
1 2 3 4 5 6 7 8 9
| import { configureStore } from '@reduxjs/toolkit' import userReducer from './modules/userSlice'
export default configureStore({ reducer: { user: userReducer, }, })
|
组件中使用
父组件注入redux
Provider
组件注入后子组件才可获取state
src/main.jsx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| import { StrictMode } from 'react' import { createRoot } from 'react-dom/client' import { Provider } from 'react-redux' import redux from './redux'
import Hello from './components/Hello' import UseRTK from './components/UseRTK'
import './redux'
createRoot(document.getElementById('root')).render( <StrictMode> <Provider store={redux}> <Hello /> <UseRTK /> </Provider> </StrictMode> )
|
组件读写state
useSelector
钩子用于获取state
, 回调函数接收的state
参数为所有的state
可用模块挂载时的属性名来筛选所需的state
模块
useDispatch
钩子用于派发方法
将userSlice
的方法传给dispatch
来使用操作state
src/components/UseRTK/index.jsx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| import { useSelector, useDispatch } from 'react-redux' import { login, logout } from '../../redux/modules/userSlice'
export default () => { const userStore = useSelector((state) => state.user) const dispatch = useDispatch()
const loginHandle = () => { dispatch( login({ name: 'test', admin: false, token: '123456', }) ) }
const logoutHandle = () => { dispatch(logout()) }
return ( <> <p>{userStore.name || '请登录'}</p> {userStore.name ? ( <button onClick={logoutHandle}>登出</button> ) : ( <button onClick={loginHandle}>登录</button> )} <p>{JSON.stringify(userStore)}</p> </> ) }
|
RTKQ请求API