用 umi 配置redux/toolkit 很是头疼,在官网也并未发现教程。umi 官方文档只给出约定式路由配置全局 layout,本人过于菜鸡以为约定式路由和配置式路由配置方式不同,后发现其实是相同的。
layout 全局
引用 umi 官方文档
umirc 配置 layout 路由
{
routes: [
{
exact: false, path: '/', component: '@/layouts/index',
routes: []
}
]
}
layout 组件
目录结构
--src
----layouts
------index.tsx
组件
import { IRouteComponentProps } from 'umi'
import store from './../store';
import { Provider } from 'react-redux';
export default function Layout({ children, location, route, history, match }: IRouteComponentProps) {
return <Provider store={store}> {children} </Provider>
}
注册slice,声明store
counterSlice.ts
export const slice = createSlice({
name: 'COUNTER',
initialState: {
value: 20,
},
reducers: {
increment: state => {
state.value += 1;
},
decrement: state => {
state.value -= 1;
},
incrementByAmount: (state, action) => {
state.value += action.payload;
},
},
});
export const { increment, decrement, incrementByAmount } = slice.actions;
export const incrementAsync = (amount: any) => (dispatch: any) => {
console.log(amount,"amount")
setTimeout(() => {
dispatch(incrementByAmount(amount));
}, 1000);
};
export const selectCount = (state: any) => state.counter.value;
export default slice.reducer;
store.ts
import counterReducer from './slice/counterSlice';
export default configureStore({
reducer: {
counter: counterReducer
},
});
总结
其他 provider 配置也可参考以上方式进行配置