Taro微信小程序開發技巧之非頁面js中使用redux的action

    • 在使用Taro開發微信小程序的過程中,經常會遇到這樣的一種情況,需要在非頁面js中更新redux保存的狀態以實現特殊場景業務,在網上搜了好久,沒有找到幾個可以用的解決方案,經過一上午的折騰,總算找到一個折中的方式實現,故在此記錄一下。

  • 正文

    • 相信在頁面組件中使用redux更新狀態大部分開發者都是信手拈來,直接 connect 一下就可以把相應的action映射到頁面組件的props中直接調用,那麼如果在非頁面js,如工具類:_tools.js中要調用action更新狀態要怎麼做呢,話不多說,直接上代碼

//app.js


import '@tarojs/async-await'
import Taro, { Component } from '@tarojs/taro'
import { Provider } from '@tarojs/redux'
import Index from './pages/index'

import configStore from './store'


const store = configStore();

class App extends Component {

  // 省略n行無關代碼...

  componentDidMount () {

    //重點:將redux的store對象掛在到Taro下,以便在任意js中訪問
    Taro.$store = store;

  }

  //省略n行無關代碼...

  // 在 App 類中的 render() 函數沒有實際作用
  // 請勿修改此函數
  render () {
    return (
      <Provider store={store}>
        <Index />
      </Provider>
    )
  }
}

Taro.render(<App />, document.getElementById('app'));


// _tools.js

import Taro from '@tarojs/taro'
import {SAVE_USERINFO} from '../constants/common'
export default {
    doLogin(){
        //調用接口獲取用戶信息,此處省略獲取用戶信息過程,直接使用res代替
        let res = {username: 'kiner'};
        Taro.$store.dispatch({type: SAVE_USERINFO,data:{userInfo:res}});
    }
};

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章