基础API
configureStore()
combineReducers()
createSlice()
createAsyncThunk()
使用步骤
一、 index.js 中 引入并包裹
import { Provider } from 'react-redux'
import store from './reducers'
二、创建 reducers 文件夹下 index.js
import { configureStore, combineReducers } from '@reduxjs/toolkit'
inport demo from './demo'
const rootReducer = combineReducers({ demo })
const store = configureStore({ reducer : rootReducer })
export type RootState = ReturnType
export default store;
三 、 demo.js
import {createSlice, createAsyncThunk } from '@reduxjs/toolkit'
const initialState={
str1 : '',
str2 : ''
};
export const setData = createAsyncThunk (
'qwe/setData',
()=>{
return 'we'
}
)
const b = createSlice({
name :'asd',
initialState,
reducers:{},
extraReducers:(bui)=>{
bui.addCase(setData.pending, (state)=>{
state.str1 = '1'
});
bui.addCase(setData.fulfilled, (state,action)=>{
console.log(action,'------')
state.str1 = action.payload || ''
});
bui.addCase(setData.rejected, (state)=>{
state.str1 = '3'
});
}
})
export default b.reducer;
// export const bActions = b.actions; // 暂时还没理解用处
四、 组件中使用
i
import './App.css';
// import { getUserInfo } from './reducers/userInfo';
import { setData } from './reducers/demo';
import { RootState } from './reducers';
function App() {
const dispatch = useDispatch();
const a = useSelector((state : RootState )=> state.demo.str1)
useEffect(()=>{
dispatch(setData())
},[dispatch]);
return (
{a}
);
}
export default App;
文档地址 : https://redux-toolkit.js.org/