美文网首页
Taro3中使用dva

Taro3中使用dva

作者: vivianXIa | 来源:发表于2021-01-19 23:56 被阅读0次

    1:在utils文件下新建一个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();
      },
    };
    

    2: 在app.tsx中

    import React, { Component } from 'react'
    import Taro from "@tarojs/taro";
    import { getStorageSync } from '@tarojs/taro';
    import Api from '@/api';
    /* dva */
    import {Provider} from 'react-redux'
    import dva from './utils/dva'
    import models from './models/index'
    
    // 全局样式
    import 'taro-ui/dist/style/index.scss'
    import './app.scss'
    
    const dvaApp = dva.createApp( {
      initialState: {},
      models: models,
    } );  
    const store = dvaApp.getStore();
    
    class App extends Component<any,any> {
    
      async componentDidMount() {
        let openid = getStorageSync('openId') || ''
        let role = getStorageSync('role') || ''
        if (process.env.TARO_ENV === 'weapp') { 
        }
      
        if (openid) { 
          let result = await Api.User.getRole({ openid });
          console.log(result);
        }
      }
    
      // 在 App 类中的 render() 函数没有实际作用
      // 请勿修改此函数
      render() {
        return (
          <Provider store={store} >
            {this.props.children }
          </Provider>
        )
      }
    }
    
    export default App
    

    3:src目录下新建一个文件夹,

    • 创建index.ts
    import common from "./common";
    // 示范 import cart from '../pages/cart/model';
    
    export default [
      common,
       ...
    ];
    
    • 创建common.ts
    import Taro from "@tarojs/taro";
    import Api from "@/api";
    import { userRole } from "@/utils/common";
    
    export default {
      namespace: "common", // 这是模块名
      state: {
        nickName: Taro.getStorageSync("nickName") || "",
        avatarUrl: Taro.getStorageSync("avatarUrl") || "",
    },
    effects: {
        // 异步方法, 在这里可以用put调用同步的方法
        // generator  这里的方法第二个参数都是{call, put }, call调用异步方法, put 可以调用reducers中的方法
        *saveStorageSync({ payload }, { call, put }) {
          for (let index = 0; index < Object.keys(payload).length; index++) {
            yield call(Taro.setStorage, {
              key: Object.keys(payload)[index],
              data: payload[Object.keys(payload)[index]],
            });
          }
          yield put({
            type: "save", // 方法名
            payload, // 参数
          });
        }
    },
     reducers: {
        // 同步方法
        save(state, { payload }) {
          return { ...state, ...payload };
        },
      },
    }
    

    4:在页面上使用

    • 在头部引入
    import { connect } from "react-redux"
    

    在主类前添加修饰符

    @connect(({ roomDetail, repair, common, fileCenter }) => ({
      title: roomDetail.roomInfo.roomName,
    }))
    export default class Index extends Component <any, PageState>{
      constructor (props) {
        super(props)
        this.state = {
          value:""
        }
      }
    

    5:如果是非类组件,如函数式组件中使用

    import dva from '@/utils/dva'
    const dispatch = dva.getDispatch()
    dispatch({
          type: 'common/saveStorageSync',
          payload: {
            accessToken: '',
            isSubscribe: false,
          },
      })
    
    
    //store  
    import dva from '@/utils/dva'
    const store = dva.getStore()
    const { common } = store.getState()
    console.log(common.accessToken)
    
    

    相关文章

      网友评论

          本文标题:Taro3中使用dva

          本文链接:https://www.haomeiwen.com/subject/inrhzktx.html