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

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

相关推荐
Java后端的Ai之路2 分钟前
03_React_JSX
前端·react.js·前端框架
百度一下吧12 分钟前
断网后 WebView 加载单页面应用:页面跳转 JS 加载失败的处理方案
开发语言·javascript·ecmascript
颜进强20 分钟前
26 · NestJS 基础篇 · 全专栏总结:五个阶段,一次收拢
前端·后端·ai编程
风寄巴山秋21 分钟前
OpenBMC:Web 页面功能异常排查
运维·服务器·前端·架构
程序员Sunday1 小时前
Promise.all、allSettled、race、any 怎么选,失败后其他请求会怎样
开发语言·前端·javascript
niucloud-admin1 小时前
JAVA V6 多商户商城 开发文档——管理端前端
前端
weixin_422201301 小时前
如何解决小程序图标点击热区小,落点不准问题?
前端·小程序·样式·点击热区·扩大
szial2 小时前
JavaScript 的 call、apply 和 bind:如何控制函数调用
开发语言·前端·javascript
。小二2 小时前
Go 泛型并发利刃:async 库深度评测——370K ops/s、零依赖、生产就绪
开发语言·javascript·golang
CopyCode2 小时前
Agent 开发不是模型训练:一个前端的入门认知
前端·llm·agent