安装
yarn add mobxyarn add mobx-react
为了能使用装饰器安装 @babel/plugin-proposal-decorators
yarn add @babel/plugin-proposal-decorators
修改 webpack 配置
yarn eject
在 package.json 中的 babel 属性中添加 plugins
"babel": {"presets": ["react-app"],"plugins": [["@babel/plugin-proposal-decorators", {"legacy": true}]]}
在 tsconfig.json 中添加 2 行配置, 参考
"experimentalDecorators": true,"useDefineForClassFields": true
使用装饰器写法定义状态
import { makeObservable, observable, action } from 'mobx'export class AuthStore {@observable isLogin = false@observable isLoading = false@observable values = {username: 'aaa',password: '',}constructor() {makeObservable(this)}@action setIsLoading(isLogin: boolean) {this.isLogin = isLogin}@action setUsername(username: string) {console.log(username)this.values.username = username}@action setPassword(password: string) {this.values.password = password}@action login() {console.log('登录中')this.isLoading = truesetTimeout(() => {console.log('登录成功')this.isLogin = truethis.isLoading = false}, 1000)}@action register() {console.log('注册中')this.isLoading = truesetTimeout(() => {console.log('注册成功')this.isLoading = false}, 1000)}@action logout() {this.isLogin = falseconsole.log('已注销')}}
定义 useStore 方法
import { createContext, useContext } from 'react'import { AuthStore } from './auth'const context = createContext({AuthStore: new AuthStore(),})export const useStore = () => useContext(context)
在组件中使用全局状态
注意 inputRef 需要将类型声明为 MutableRefObject
import { useStore } from '../store'import { observer } from 'mobx-react'import { MutableRefObject, useRef } from 'react'const Login = observer(() => {const { AuthStore } = useStore()const inputRef = useRef() as MutableRefObject<HTMLInputElement>const handleInput = () => {AuthStore.setUsername(inputRef.current.value)}return (<><div>Login: {AuthStore.values.username}</div><input type="text" onChange={handleInput} ref={inputRef} /></>)})export default Login
