1. Create a main store

// sotre/index.ts

// We created a sub-repository of user
import UserStore, { User } from './user/user'

const user = new UserStore()

// Define the warehouse type
export interface StoreType {
    user: User
}


const stores: StoreType = {
    user
}

export default stores
Copy the code

2. Import the main repository in ts of main

import { Provider } from 'mobx-react'
import stores from './store/index'

// You need to wrap the Provider
ReactDOM.render(
  <Provider {. stores} >
    <App />
  </Provider>.document.getElementById('root'))Copy the code
3. Write the User repository
// user/user.ts
import { makeAutoObservable } from 'mobx';

export interface User {
    name: string
    password: string
    userInfo: string
    loginAction: (payload: { name: string, password: string }) = > void
}

class UserStore implements User {
    // state
    name = ' '
    password = ' '

    constructor() {
        // Look at all the data
        makeAutoObservable(this)}// getter
    get userInfo() {
        return this.name + ' ' + this.password
    }

    // action
    loginAction(payload: { name: string; password: string; }) :void {
        this.name = payload.name
        this.password = payload.password
        console.log(this)
        console.log('Login successful')}}export default UserStore
Copy the code

4. Separate action methods

// Create an actions file
export default class actions {
    loginAction(payload: { name: string; password: string; }) :void {
        this.name = payload.name
        this.password = payload.password
        console.log(this)
        console.log('Login successful')}}// Reformat the user.ts method while importing actions
import actions from './actios'

loginAction(payload: { name: string, password: string }){}// Implement actios simultaneously
class UserStore implements User.actions// Create onemixinWith the functionfunction applyMixins(derivedCtor: any.baseCtors: any[]) {
    baseCtors.forEach(baseCtor= > {
        Object.getOwnPropertyNames(baseCtor.prototype).forEach(name= > {
            derivedCtor.prototype[name] = baseCtor.prototype[name]
        })
    })
}

// Put actions in the user class
applyMixins(UserStore, [actions])
Copy the code

5. Use Store in your page

import React from 'react'
import { inject, observer } from 'mobx-react'
import { StoreType } from './store/index'

function App({ user }: StoreType) {

  const login = () = > {
     / / use the actions
    user.loginAction({ name: 'zs'.password: '123456789'})}return (
    <div>
      <div>{* Use state data *}<p>UserInfo:{user.name}</p>
        <p>{user.password}</p>
        <p>getter: {user.userInfo}</p>
      </div>
      <div>
        <button onClick={login}>The login</button>
      </div>
    </div>)}export default inject('user')(observer(App))
Copy the code