redux-toolkit使用

安装 npm i @reduxjs/toolkit

创建store

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import { configureStore } from '@reduxjs/toolkit'
import CounterReducer from './counter.slice'


export const store = configureStore({
reducer: {
counter: CounterReducer
},
})

// 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

创建slice

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'
import { PayloadAction, createAsyncThunk } from '@reduxjs/toolkit'

export interface CounterState {
value: number
}

const initialState: CounterState = {
value: 0,
}

export const counterSlice = createSlice({
name: 'counter',
initialState,
reducers: {
increment: (state) => {
state.value += 1
},
decrement: (state) => {
state.value -= 1
},
incrementByAmount: (state, action: PayloadAction<number>) => {
state.value += action.payload
},
},
})

// Action creators are generated for each case reducer function
export const { increment, decrement, incrementByAmount } = counterSlice.actions

export default counterSlice.reducer

使用

根组件

1
2
3
4
5
6
7
8
9
10
11
12
13
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App'
import {Provider } from 'react-redux'
import {store} from './store'

ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>
)

子组件

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
import { useDispatch, useSelector } from 'react-redux'
import { RootState } from './store'
import { increment, decrement, incrementByAmount, incrementAsync } from './counter.slice'

function App() {
// 使用值
const count = useSelector((state: RootState) => state.counter.value)
// 触发
const dispatch = useDispatch()

return (
<div className="App">
<div className="card">
<button onClick={() => { dispatch(increment()) }}>
+
</button>
<button onClick={() => { dispatch(decrement()) }}>
-
</button>
<button onClick={() => { dispatch(incrementByAmount(10)) }}>
+10
</button>
<div>
count is {count}
</div>
</div>
</div>
)
}
作者

建指所向

发布于

2022-09-23

更新于

2023-11-07

许可协议