【问题标题】:MobX observable with dynamic dataMobX 可观察到的动态数据
【发布时间】:2017-08-31 23:37:30
【问题描述】:

我有以下课程

export default class BaseStore {
  @observable model ;

  @action updateStore(propertyName, newValue) {
    this.model[propertyName] = newValue;
  }
}

在子类中,我向可观察模型添加层,例如:

model.payment.type = 'credit card'

发生这种情况时,我的反应组件不会自动呈现,但是,如果我有顶级数据,例如:

model.Type = 'CreditCard'

我是 MobX 的新手,并且读到我需要使用 map(),但我找不到一个合适的示例来解释如何使用它。

【问题讨论】:

  • 当你说“在子类中我向可观察模型添加层”时,你是什么意思?您能否分享将添加到模型的确切代码片段?

标签: reactjs mobx mobx-react


【解决方案1】:

如果您知道model 将拥有的所有键,您可以使用null 值初始化它们,observer 组件将重新渲染。

示例 (JSBin)

class BaseStore {
  @observable model = {
    type: null
  };

  @action updateStore(propertyName, newValue) {
    this.model[propertyName] = newValue;
  }
}

const baseStore = new BaseStore();

@observer
class App extends Component {
  componentDidMount() {
    setTimeout(() => baseStore.model.type = 'CreditCard', 2000);
  }

  render() {
    return <div> { baseStore.model.type } </div>;
  }
}

如果你事先不知道model 的所有键,你可以像你说的那样使用map

示例 (JSBin)

class BaseStore {
  model = observable.map({});

  @action updateStore(propertyName, newValue) {
    this.model.set(propertyName, newValue);
  }
}

const baseStore = new BaseStore();

@observer
class App extends Component {
  componentDidMount() {
    this.interval = setInterval(() => {
      const key = Math.random().toString(36).substring(7);
      const val = Math.random().toString(36).substring(7);
      baseStore.updateStore(key, val);
    }, 1000);
  }

  componentWillUnmount() {
    clearInterval(this.interval);
  }

  render() {
    return <div> 
      { baseStore.model.entries().map(e => <div> {`${e[0]} ${e[1]}` } </div>) } 
    </div>;
  }
}

【讨论】:

  • 我的问题是更深层次的项目,例如:model.input.card.number // 作为示例,这种情况不会触发“渲染”功能
  • 我只从模型开始,我希望在运行时开始添加诸如此层次结构之类的项目:model.Payment.CreditCard.Amount。我希望我的渲染在我更改数量时调用,尽管原始观察者直到程序生命周期的后期才拥有这个项目。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-09
  • 1970-01-01
相关资源
最近更新 更多