Reactjs 动态数据可观测的MobX
我有以下课程Reactjs 动态数据可观测的MobX,reactjs,mobx,mobx-react,Reactjs,Mobx,Mobx React,我有以下课程 export default class BaseStore { @observable model ; @action updateStore(propertyName, newValue) { this.model[propertyName] = newValue; } } 在子类中,我将层添加到可观察模型中,例如: model.payment.type = 'credit card' 发生这种情况时,我的react组件不会自动渲染,但是,如果我有顶级
export default class BaseStore {
@observable model ;
@action updateStore(propertyName, newValue) {
this.model[propertyName] = newValue;
}
}
在子类中,我将层添加到可观察模型中,例如:
model.payment.type = 'credit card'
发生这种情况时,我的react组件不会自动渲染,但是,如果我有顶级数据,例如:
model.Type = 'CreditCard'
我是MobX新手,读到我需要使用map(),但我找不到一个像样的例子来解释如何使用它。如果你知道
模型
将拥有的所有键,你可以用null
值初始化它们,然后观察者
组件将重新渲染
示例()
我的问题在于更深层次的项目,例如:model.input.card.number//作为一个示例,这种情况不会触发“呈现”功能。我只从model开始,我希望在运行时开始添加诸如以下层次结构的项目:model.Payment.CreditCard.Amount。我希望在更改数量时调用渲染,尽管原始观察者直到程序生命周期的后期才拥有此项。当您说“在子类中,我将层添加到可观察模型”时是什么意思?你能分享给模型添加图层的代码片段吗?
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>;
}
}
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>;
}
}