2017-08-31 83 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