UNPKG

react-app-shell

Version:

react打包脚本和example, 这里的版本请忽略

133 lines (117 loc) 3.07 kB
import {observable, computed, action} from 'mobx'; const getNumber = () => { return new Promise((resolve, reject) => { setTimeout(() => { resolve(1); }, 1000); }); }; const getErrorNumber = () => { return new Promise((resolve, reject) => { setTimeout(() => { reject('异常信息'); }, 1000); }); }; /** * 用户数据 */ class DemoStore { /** * 数据源 */ @observable state = { userName: '', fullName: '', noUseRandom: 0, random: 0, count: 0, userInfo: { a: '123', time: 0, random: 0, }, }; /** * 计算 * @returns {boolean} */ @computed get isAdmin() { return this.state.userName === 'admin'; } /** * 计算, 会缓存值 * @returns {boolean} */ @computed get isEven() { return this.state.random % 2 === 0; } /** * 更新没有依赖的属性 * @param value */ @action setNoUseRandom = (value) => { this.state.noUseRandom = value; console.log('this.state', this.state); }; /** * 更新有依赖的属性 * @param value */ @action setRandom = (value) => { this.state.random = value; console.log('this.state', this.state); }; /** * 异步执行 * @returns {Promise<*>} */ @action asyncUpdateCount = async () => { const value1 = await getNumber(); // const value2 = await getNumber(); // const value3 = await getNumber(); const sum = this.state.count + value1; this.state.count = sum; this.state.count = sum + 1; this.state.random = sum + 1; console.log('this.state', this.state); return sum; }; /** * 异步执行 * @returns {Promise<*>} */ @action handleAllAsyncModify = async () => { const [value1, value2] = await Promise.all([getNumber(), getNumber()]); const value3 = await getNumber(); const sum = this.state.count + value1 + value2 + value3; this.state.count = sum; console.log('this.state', this.state); return sum; }; /** * 异步执行中有异常 * @returns {Promise<*>} */ @action async asyncThrowError() { const value1 = await getNumber(); // throw new Error("我是自定义错误"); const [value2, value3] = await Promise.all([getErrorNumber(), getNumber()]); const sum = this.state.count + value1 + value2 + value3; this.state.count = sum; console.log('this.state', this.state); return sum; } @action async testAssign() { await getNumber(); this.state.userInfo.time = new Date().getTime(); this.state.userInfo.random = new Date().getTime(); this.state.userInfo = { ...this.state.userInfo, time2: new Date().getTime(), }; } } export default new DemoStore();