原生小程序开发技巧

状态管理: mp-store

下载使用: https://cdn.jsdelivr.net/gh/imtaotao/mp-store/dist/mpstore.esm.js

  • 使用

// app.js
import createStore from "./store/mpstore.esm";
const store = createStore();
wx.setStorageSync("test", "zuikaishi");
store.add("action", {
  partialState: {
    name: wx.getStorageSync("test"),
  },
  setter(state, payload) {
    return { name: payload };
  },
});
App({});

// pages\index\index.js
const app = getApp();
Page({
  storeConfig: {
    useState: (store) => ({
      name: (state) => state.name,
    }),
  },
  onShow() {
    console.log("onShow", this.data.global.name); // tao
    console.log("app", app); // tao
  },
  // 更改
  setd() {
    this.store.dispatch("action", "chentao");
    console.log(this.data.global.name); // chentao
  },
});

请求操作:miniprogram-network

需要 npm 安装使用,并在开发者工具[构建 npm]会自动把 node_modules 里面文件放置到 miniprogram_npm 文件夹

下载使用: https://github.com/landluck/iny-bus/blob/master/dist/index.js

// app.js
const Network = require("miniprogram-network");
Network.setConfig("baseURL", "https://miniprogram-network.newfuture.cc/");
// request_next.js
Network.setConfig("headers", {
  token: store.state.token, // 使用状态管理的变量token
});
// pages\index\index.js
const Network = require("miniprogram-network");
Page({
  onShow() {
    // setConfig设置所有网络请求的全局默认配置,一次定义,所有文件中使用均生效
    Network.post("index.html", { data: 1 })
      .then((res) => console.log(res))
      .finally(() => {
        console.info("done");
      });
  },
});

promise 操作:wx-promise-pro

下载使用: https://github.com/youngjuning/wx-promise-pro/blob/master/dist/wx-promise-pro.js

// 现有部分api是默认支持: 以 Promise 风格 调用:支持
// 不支持的化使用: wx.pro
// app.js
import { promisifyAll, promisify } from "./store/wx-promise-pro";
App({
  onLaunch() {
    promisifyAll();
  },
});

// pages\index\index.js
Page({
  // 更改
  async setd() {
    var res = await wx.pro
      .getUserProfile({
        desc: "展示用户信息",
      })
      .catch((re, data) => {
        console.log(re, data); // {errMsg: "getUserProfile:fail auth deny"} undefined
      });
    console.log(res);
  },
});

事件通知: iny-bus

// app.js
import bus from "./store/iny-bus";
App({
  onLaunch() {
    bus.on("postMessage", (a, b, c, d) => {
      // 支持多参数
      console.log(a, b, c, d);
    });
  },
});

// pages\index\index.js
import bus from "../../store/iny-bus";
Page({
  // 更改
  setd() {
    bus.emit("postMessage", "hello bus");
  },
});