setShopMessageStore(message: any) {
this.shopMessageStore = message;
if (process.env.TARO_ENV === 'h5') {
const overdueTime = new Date().getTime() + 15 * 60 *1000; // 设置一个数据可以缓存的时间
setSyncStorage('SHOP_MESSAGE_STORE', { ...message, overdueTime }) // 这是一个把数据缓存到本地的方法
}
}
getShopMessageStore() {
if (process.env.TARO_ENV === 'h5') {
if (!!Object.keys(this.shopMessageStore).length) {
return this.shopMessageStore; // 这里先是判断,当前mobx是否有数据,如果没,证明页面被刷新了 ,就从缓存里取
} else {
const shopMessageStoreStorage = getSyncStorage('SHOP_MESSAGE_STORE');
const nowTime = new Date().getTime();
if (shopMessageStoreStorage && nowTime < shopMessageStoreStorage?.overdueTime) { // 这里判断,缓存数据是否过期
const { overdueTime, ...rest } = shopMessageStoreStorage;
return rest;
} else {
removeSyncStorage('SHOP_MESSAGE_STORE');
Toast.show({ title: i18n.t(`order:order.info.expired`, '订单信息已过期'), icon: 'none' });
// 数据过期,就跳转回上一页或者首页等待
setTimeout(() => {
Router.navigateBack();
}, 100)
return {};
}
}
} else {
return this.shopMessageStore;
}
}
----------------------
老是忘记,这里顺便记一下,如何初始化一个 mobx的子store,数据对应上面的内容
export default class PurchaseOrderStore implements PurchaseOrderStoreModel {
shopMessageStore: any = {};
constructor(rootStore: RootStoreModel) {
makeObservable(this, {
shopMessageStore: observable
setShopMessageStore: action.bound,
}
}
}
----------------------
老是忘记,这里顺便记一下,如何初始化一个 mobx的store,数据对应上面的内容
import React, { FC, createContext, ReactNode, ReactElement, useContext } from 'react';
export const StoreContext = createContext({});
export const StoreProvider: StoreComponent = ({ children, store }): ReactElement => (
<StoreContext.Provider value={store}>{children}</StoreContext.Provider>
);
/**
* 在组件中使用这个 hooks 来导入mobx的子store
*/
export const useStores = (): RootStoreModel => useContext(StoreContext);
// ------------
import PurchaseOrderStore from '../purchaseOrderStore'
class RootStore {
purchaseOrderStore: any
constructor() {
this.purchaseOrderStore = new PurchaseOrderStore(this)
}
}
// -------------
import RootStore from './rootStore';
const rootStore = new RootStore();
const Store = {
...rootStore,
};
export default Store;
// App.tsx
<StoreProvider store={Store}>
{this.props.children}
</StoreProvider>