westore icon indicating copy to clipboard operation
westore copied to clipboard

新手问题

Open LS1231 opened this issue 4 years ago • 1 comments

1、请求应该放在store中还是model中进行? 2、假如在页面的onLoad中,我需要根据store的数据进行一些判断(store里的数据是需要请求获取到的),然而用this.data.xxx获取不到,代码如下:

model

import api from '../api/index';

class Metadata {
  constructor(options) {
    this.dict = {};
    this.webSwitch = {};
    this.webConfig = {};
    this.isOpenSubstation = false;
    this.options = options;
  }

  async getMetadata() {
    const [{ data: dict }, { data: webConfig }, { data: webSwitch }] = await Promise.all([
      api.common.getDict(),
      api.common.getWebConfig(),
      api.common.getWebSwitch()
    ]);

    this.dict = dict;
    this.webSwitch = webSwitch;
    this.webConfig = webConfig;
    this.isOpenSubstation = Boolean(dict.SITE_LIST && dict.SITE_LIST.length > 0);
    this.options.onMetadataLoaded && this.options.onMetadataLoaded();
  }
}

export default Metadata;

store

import { Store } from 'westore';
import Metadata from '../models/metadata';
class MetadataStore extends Store {
  constructor(options) {
    super();
    this.options = options;
    this.data = {
      dict: {},
      webConfig: {},
      webSwitch: {},
      isOpenSubstation: false
    };

    this.metadata = new Metadata({
      onMetadataLoaded: () => {
        this.data.dict = this.metadata.dict;
        this.data.webConfig = this.metadata.webConfig;
        this.data.webSwitch = this.metadata.webSwitch;
        this.data.isOpenSubstation = this.metadata.isOpenSubstation;
        this.update();
      }
    });
  }

  getMetadata() {
    this.metadata.getMetadata();
  }
}

export default new MetadataStore();

view

import metadataStore from '../../stores/metadata-store';
Page({
  data: metadataStore.data,
  onLoad() {
    metadataStore.bind(this);
    metadataStore.getMetadata();
    // 这里获取不到webSitch
    if (this.data.webSwitch.near_jobs_status) {
      // do something
    }
  }
})

LS1231 avatar Oct 10 '21 14:10 LS1231

1、请求应该放在store中还是model中进行?

我倾向于放到 store 中,model 只管数据注入,不管数据请求

2、假如在页面的onLoad中,我需要根据store的数据进行一些判断(store里的数据是需要请求获取到的),然而用this.data.xxx获取不到,

a. getMetadata 是异步所以取不到啊

  async onLoad() {
    metadataStore.bind(this);
    await metadataStore.getMetadata();
    // 这里获取不到webSitch
    if (this.data.webSwitch.near_jobs_status) {
      // do something
    }
  }

b.你不用到把逻辑写到 onLoad 里

dntzhang avatar Oct 11 '21 08:10 dntzhang