npm install redux-toolkit
1.数据流
上代码
2.Home/homeSlice.js
import { createAsyncThunk, createSlice } from '@reduxjs/toolkit';
import * as service from '../service'; // API
// 网络请求
export const getBasicInfo = createAsyncThunk(
'home/getBasicInfo',
(params, thunkAPI) => {
console.log('dispatchParams', params);
return service.getBasicInfo();
}
);
const homeSlice = createSlice({
name: 'home',
initialState: {
value: 0,
loading: 'idle',
userPoints: {},
quickEntrance: [],
banner: [],
},
reducers: {
increment(state) {
state.value++;
},
decrement(state) {
state.value--;
},
setValue(state, {payload}) {
state.value = payload
},
extraReducers: builder => {
builder.addCase(getBasicInfo.pending, (state, action) => {
state.loading = 'pending';
});
// 接口请求返回
builder.addCase(getBasicInfo.fulfilled, (state, { payload }) => {
state.loading = 'fulfilled';
// 这里处理数据
state.userPoints = payload.userPoints;
state.banner = payload.banner;
state.quickEntrance = payload.quickEntrance;
});
builder.addCase(getBasicInfo.rejected, (state, action) => {
state.loading = 'failure';
});
},
});
// actions
export const { increment, decrement, setValue } = homeSlice.actions;
// reducers
export default homeSlice.reducer;
3.store/index.js
// 辅助函数
import { configureStore, combineReducers } from '@reduxjs/toolkit';
import homeSlice from '../Home/homeSlice';
const reducer = combineReducers({
home: homeSlice,
});
const store = configureStore({
reducer,
});
export default store;
4.组件Home/home.jsx
import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { getBasicInfo, setValue } from './homeSlice';
export default function Home() {
const { value, loading, userPoints, quickEntrance, banner }= useSelector(state => state.home);
const dispatch = useDispatch();
// 防抖
const getBasicInfo = () => {
dispatch(getBasicInfo({ userinfo: 1234567 }));
dispatch(setValue(2));
};
console.log(value);
return (
<div>{value}</div>
);
}
5.出口index.js
import React from 'react';
import ReactDOM from 'react-dom';
// 跨组件状态共享
import { Provider } from 'react-redux';
import BasicRoute from './router';
import store from './store';
import './assets/style/index.less';
// ios scrollTo平滑移动兼容
import smoothscroll from 'smoothscroll-polyfill';
smoothscroll.polyfill();
import '@/styles/base.less';
import 'zarm/dist/zarm.css';
ReactDOM.render(
<>
<Provider store={store}>
<BasicRoute />
</Provider>
</>,
document.querySelector('#app')
);