React Redux Toolkit (RTK)

本文最后更新于: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) // > 'user/login'

state.name = action.payload.name
state.admin = action.payload.admin
state.token = action.payload.token
},
},
})

// userSlice.actions存储了操作该state的方法集导出以供使用
export const { logout, login } = userSlice.actions
// userSlice.reducer用来创建模块
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


React Redux Toolkit (RTK)
https://qingshaner.com/ReactRedux与RTK/
作者
清山
发布于
2022年10月29日
许可协议