发表更新1 分钟读完 (大约211个字)
redux-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 }, })
export type RootState = ReturnType<typeof store.getState>
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 }, }, })
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> ) }
|