taro 引入dva框架

1、安装

    redux:
         cnpm install --save redux @tarojs/redux @tarojs/redux-h5 redux-thunk redux-logger
   dva:
         cnpm install --save dva-core dva-loading
       ps: dva-loading 与dva-core 是版本依赖的,如果安装dva-loading时出错,请按要求安装相应版本的dva-core, 如dva-core@1.6.0-beta.6 dva-loading@3.0.12
 
 
2、配置dva,  src/utils/dva.js
     
import Taro from '@tarojs/taro';
import { create } from 'dva-core';
// import { createLogger } from 'redux-logger';
import "@tarojs/async-await";
import createLoading from 'dva-loading';

let app;
let store;
let dispatch;

function createApp(opt) {
// redux日志
// opt.onAction = [createLogger()];
app = create(opt);
app.use(createLoading({}));

// 适配支付宝小程序
if (Taro.getEnv() === Taro.ENV_TYPE.ALIPAY) {
global = {};
}

if (!global.registered) opt.models.forEach(model => app.model(model));
global.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;
},
};
  
3、配置model,src/models/index.js
 
//配置dvaApp的models
import common from './common'

//各个page的models都需要在这里"注册"
export default [
common
]
 
4、引入dva,  src/app.js
 
import Taro, { Component } from '@tarojs/taro'
import '@tarojs/async-await'
import { Provider } from "@tarojs/redux";
import dva from './utils/dva'
import models from './models';
import Index from './pages/home'
import './app.scss'
//引入 taro-ui
import 'taro-ui/dist/style/index.scss'
// 如果需要在 h5 环境中开启 React Devtools
// 取消以下注释:
// if (process.env.NODE_ENV !== 'production' && process.env.TARO_ENV === 'h5') {
// require('nerv-devtools')
// }
const dvaApp = dva.createApp({
initialState: {},
models: models,
});
const store = dvaApp.getStore();

class App extends Component {

config = {
pages: [
'pages/home/index'
],
window: {
backgroundTextStyle: 'light',
navigationBarBackgroundColor: '#fff',
navigationBarTitleText: 'WeChat',
navigationBarTextStyle: 'black'
}
}

componentDidMount () {}
componentDidShow () {}
componentDidHide () {}
componentDidCatchError () {}
// 在 App 类中的 render() 函数没有实际作用
// 请勿修改此函数
render () {
return (
<Provider store={store}>
<Index />
</Provider>
)
}
}
Taro.render(<App />, document.getElementById('app'))
 
5、配置action ,utils/action.js
 
const action = (type, payload) => ({type, payload});

export default action

6、使用
 
     a、创建models,models/common.js
import action from "../utils/action";
import {request} from "../utils/request";

export default {
namespace: 'common',
state: {
list: []
},
reducers: {
save(state, {payload}) {
return {...state, ...payload};
},
},
effects: {
* load({payload}, {call, put}) {
console.log("common",payload)
let data = yield call(request,payload);
console.log("response",data)
yield put(action("save", {list: data}))
},
},
};
 
    b、连接组件
import Taro, { Component } from '@tarojs/taro'
import { View, Text } from '@tarojs/components'
import { AtTabBar } from 'taro-ui'
import {connect} from '@tarojs/redux'
import action from '../../utils/action'

import './index.scss'

@connect(({common, loading}) => ({
...common,
isLoad: loading.effects["common/load"],
}))
export default class Index extends Component {
config = {
navigationBarTitleText: '热榜'
}
constructor() {
super(...arguments)
this.state={
current: 0,

}
}
componentDidMount () {

const{dispatch}=this.props
dispatch(action("common/load",{
"svr_name": "AdDeviceMngSvr",
"method_name": "GetDeviceSearchList",
"req_body": {
"iUid": 1,
"sToken": ''
}
}));
}}
 c、发起请求
   
import Taro from '@tarojs/taro'
import '@tarojs/async-await'

export function request(params) {
const data = JSON.stringify(params)
const method = 'post'
const url = 'https://www.xxx.cn/comm_route'
const opt={
data:data,
method:method,
url:url
}
return Taro.request(opt).then((res) => {
console.log("res",res)
let {statusCode, data} = res;
if (statusCode >= 200 && statusCode < 300) {
return data;
} else {
throw new Error(`网络请求错误,状态码${statusCode}`);
}
})
}
 
posted @ 2021-03-02 20:05  似是故人来~  阅读(923)  评论(0编辑  收藏  举报