构建Taro公众号工程(二)
目的:配置Dva并使用
1.创建dva的store
- 创建dva文件
目录 src/utils/dva/dva.ts
import { create } from "dva-core";
// import {createLogger } from 'redux-logger';
import createLoading from "dva-loading";
let app: {
use: (arg0: any) => void;
model: (arg0: any) => any;
start: () => void;
_store: any;
getStore: () => any;
dispatch: any;
};
let store: { dispatch: any };
let dispatch: any;
let registered: boolean;
function createApp(opt: { models: any[]; initialState: any }) {
// redux日志, 引用redux-logger
// opt.onAction = [createLogger()];
app = create(opt);
app.use(createLoading({}));
if (!registered) opt.models.forEach((model: any) => app.model(model));
registered = true;
app.start();
store = app._store;
app.getStore = () => store;
dispatch = store.dispatch;
app.dispatch = dispatch;
return app;
}
export default {
createApp,
getDispatch() {
return app.dispatch;
},
getStore() {
// 这个是在非组件的文件中获取Store的方法, 不需要可以不暴露
return app.getStore();
}
};
- 创建models.ts,用于存放自定义model
目录:src/utils/dva/models.ts
export default [];
- 创建store.ts
目录:src/utils/dva/store.ts
import dva from "@/utils/dva/dva";
import models from "@/utils/dva/models";
const dvaApp = dva.createApp({
initialState: {},
models: models
});
const store = dvaApp.getStore();
export default store;
- 在app.tsx中,进行包裹
import "@/utils/global";
import "./app.less";
/**dva */
import { Provider } from "react-redux";
import store from "@/utils/dva/store";
import VConsole from "vconsole";
const isDev = process.env.NODE_ENV === "development";
isDev && new VConsole();
export default props => {
return <Provider store={store}>{props.children}</Provider>;
};
评论区