Example of using mobx to manage state data in React

MobX is a battle-tested library that makes state management simple and scalable by using Transparent Functional Reactive Programming (TFRP). Official website address: About MobX | MobX Chinese Documentation | MobX Chinese Website

install dependencies

mobx-react-lite is a dependency library for mobx and react to establish a link, and it must be installed before it can be used

yarn add mobx 


yarn add mobx-react-lite

Create one or more stores

And use store/index.js for unified management, so that you only need to use a unified method in the future

CountStore.js: a store for storing data

import { makeAutoObservable } from "mobx"


class CountStore {
  count = 0
  constructor() {
    makeAutoObservable(this)
  }

  addCount = () => {
    this.count++
  }
}


export default CountStore

Unified management index.js:

import CountStore from "./count";
import MyInfo from "./info";
import React from "react";

class Store {
  constructor() {
    this.countStore = new CountStore()
    this.myInfo = new MyInfo()
  }
}

// 使用context是为了让react识别到Store里面的mobx,不然react不认识Store
const rootStore = new Store()
const context = React.createContext(rootStore)
export const useStore = () => React.useContext(context)

used in build

Use store like hooks, or use destructuring assignment to destructure countStore:

import React from 'react'
import { useStore } from './store'
import { observer } from 'mobx-react-lite'

function App() {
    const { countStore, myInfo } = useStore()

    return (
        <div>
            <h2>APP组件</h2>
            <div className="count-box">
                count状态: {countStore.count}
                <button onClick={countStore.addCount}>+</button>
            </div>
            <div>
                myinfo状态: {myInfo.myCar.join('++')}
                myAge状态: {myInfo.FilterAge.join('||')}
                <button onClick={myInfo.addCar}>修改内容</button>
            </div>
        </div>
    )
}

export default observer(App)

Effect

You can debug and view the data in the React building, find the corresponding component, then check the Context property under Hooks, find the one with the store in it, and open it to view the data stored in it

 

 

Guess you like

Origin blog.csdn.net/weixin_44786530/article/details/132186875
Recommended