taro3中使用react函数组件和mobx状管理工具结合使用教程

在使用了最新版的函数组件hooks后,刚开始导入mobx,总是报cant resolve "src/store/index"这种错误,然后我就开始一步一步找原因,后来在组件中log了一下store,重新启动程序后,就没问题了,我也是无语.....

下面看一下taro使用react函数组件接入mobx的流程:

先在store下面创建一个counter.ts:

javascript 复制代码
import { observable } from "mobx";

const counterStore = observable({
  counter: 100,
  addStore() {
    this.counter++;
  },
  increment() {
    this.counter++;
  },
  decrement() {
    this.counter--;
  },
  incrementAsync() {
    setTimeout(() => {
      this.counter++;
    }, 1000);
  },
});

export default counterStore;

然后再创建一个store/index.ts:

javascript 复制代码
import React from "react";
import counterStore from "./counter";

const storesContext = React.createContext({
  counterStore,
});

// 默认导出
export default storesContext;

然后看一下我的app.tsx:

javascript 复制代码
import { Component, PropsWithChildren } from "react";
import "./app.scss";

class App extends Component<PropsWithChildren> {
  componentDidMount() {}

  componentDidShow() {}

  componentDidHide() {}

  // this.props.children 就是要渲染的页面
  render() {
    return this.props.children;
  }
}

export default App;

然后开始在组件中使用这个mobx状态管理:

javascript 复制代码
import { useContext, useEffect, useState } from "react";
import { View, Button, Text } from "@tarojs/components";
import { observer } from "mobx-react";
import Store from "../../store/index";
import "./index.scss";

function Index() {
  const [count, setCount] = useState(0);

  const { counterStore } = useContext(Store);

  useEffect(() => {
    console.log("store", counterStore);
  });

  // 点击按钮改变store状态
  const handleClick = () => {
    // 修改mobx中的数据状态
    counterStore.addStore();
    // 修改组件中的数据状态
    setCount(count + 1);
  };

  return (
    <View>
      <Text>
        函数组件状态:{count} || mobx中的状态: {counterStore.counter}
      </Text>
      <Button onClick={() => handleClick()}>+1</Button>
    </View>
  );
}

export default observer(Index);

最后点击即可实现状态控制:

相关推荐
神奇的程序员7 小时前
我的软件冲进苹果商店下载榜前 50 了
前端
阳光是sunny7 小时前
别再被 worktree 绕晕了!AI 编程时代你必须掌握的 Git 隔离神器
前端·人工智能·后端
万少8 小时前
万少的博客 - 技术分享与解决方案
前端·javascript·后端
尘世中一位迷途小书童11 小时前
用 Cesium 撸了一个森林火情监控大屏,弧线、粒子、发光效果都齐了
前端·javascript
IT_陈寒11 小时前
垃圾回收器选错了,我的Java服务内存炸了
前端·人工智能·后端
月光下的丝瓜12 小时前
Flutter 国内安装指南
前端·flutter
先吃饱再说12 小时前
JavaScript中`this` 的“千层套路”:从默认绑定到箭头函数的五种指向
javascript
玄星啊12 小时前
AI 编程的第 30 天,我怀念古法 Coding 了
前端·ai编程
Jolyne_12 小时前
Angular基础速通
前端·angular.js
foxire13 小时前
基于nodejs实现服务端内核引擎
javascript