2017-08-31 82 views
0

我有下面的类与动态数据

export default class BaseStore { 
    @observable model ; 

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

子类中我添加图层到观察的模型,如MobX观察到:

model.payment.type = 'credit card' 

我的反应成分不会自动呈现时然而,如果我有顶级数据,例如:

model.Type = 'CreditCard' 

我是MobX的新手,阅读我需要使用map(),但我无法找到解释如何使用它的体面的例子。

+0

你是什么意思,当你sa y'在子类中,我将图层添加到可观察模型'?您能否分享将_layers_添加到模型的确切代码段? – Alik

回答

0

如果您知道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>; 
    } 
} 
+0

我的问题是与更深的项目,如: model.input.card.number //作为一个例子 这种情况下不触发“渲染”功能 – Pacman

+0

我开始只是模型,我想在运行时开始添加项目如这个层次结构:model.Payment.CreditCard.Amount。我希望我的渲染在我更改金额时调用,尽管原始观察者在程序的生命周期中稍后才有此项目。 – Pacman