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);

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

相关推荐
qingyingWin11 分钟前
原生微信小程序研发,如何对图片进行统一管理?
前端·微信小程序
不懂英语的程序猿21 分钟前
【JEECG】JVxeTable表格拖拽排序功能
前端·后端
拾光拾趣录26 分钟前
前端灵魂拷问:从URL到Redux,17个常见问题
前端·面试
萌萌哒草头将军34 分钟前
Prisma ORM 又双叒叕发布新版本了!🚀🚀🚀
前端·javascript·node.js
mldong1 小时前
推荐一款超高颜值的后台管理模板!Art-Design-Pro!开源!免费!
前端·vue.js·架构
草字1 小时前
uniapp 如果进入页面输入框自动聚焦,此时快速返回页面或者跳转到下一个页面,输入法顶上来的页面出现半屏的黑屏问题。
java·前端·uni-app
我是ed.1 小时前
cocos Js 使用 webview 通过 postMessage 进行通信
开发语言·javascript·ecmascript
程序视点1 小时前
Wise Duplicate Finder 重复文件查找工具 - 永久免费专业版文件去重工具
前端·windows
一点一木2 小时前
🚀 2025 年 07 月 GitHub 十大热门项目排行榜 🔥
前端·人工智能·github
脑袋大大的3 小时前
uni-app x开发避坑指南:拯救被卡顿的UI线程!
开发语言·前端·javascript·vue.js·ui·uni-app·uts