2017-10-19 66 views
2

反應做自動運行反應必須是構造內才能工作? 我可以寫這個簡單的例子嗎?構造函數MobX自動運行和內部構造

此外,我在自動運行內運行的代碼正常運行,但如果將其更改爲console.log(this.expenses),則不起作用。這是爲什麼?

import { observable, action, computed, useStrict, autorun, reaction } from 'mobx' 
useStrict(true) 

class ExpensesStore { 

    @observable.shallow expenses = [] 

    @action addExpense = (expense) => { 
    this.expenses.push(expense) 
    } 

    @computed get getExpense() { 
    if(this.expenses.length > 0) { 
     return `This is computed from ${this.expenses[0] + this.expenses[1]}` 
    } 

    } 


    constructor() { 
    autorun(() => { 
     console.log(`${this.expenses}`) 
    }) 

    reaction(
    ()=>this.expenses.map(expense => expense), expense => console.log(expense) 
    ) 
    } 


} 

const store = window.store= new ExpensesStore() 

export default store 

回答

1

自動運行反應不必是在構造。例如,你可以做到這一點,如果你喜歡:

class ExpensesStore { 
    @observable.shallow expenses = [] 

    @action addExpense = (expense) => { 
    this.expenses.push(expense) 
    } 

    @computed get getExpense() { 
    if(this.expenses.length > 0) { 
     return `This is computed from ${this.expenses[0] + this.expenses[1]}` 
    } 
    } 
} 

const store = new ExpensesStore() 

autorun(() => { 
    console.log(`${store.expenses}`) 
}) 

reaction(
() => store.expenses.map(expense => expense), expense => console.log(expense) 
) 

之所以console.log(`${this.expenses}`)作品和console.log(this.expenses)不會是因爲你當你寫this.expenses不取消引用您的淺陣列東西。

當你寫...

`${this.expenses}` 

...你是隱式調用this.expensestoString()。您可以使用toJSslice得到不把它在一個字符串時相同的效果:

例(JSBin

class ExpensesStore { 
    @observable.shallow expenses = [] 

    @action addExpense = (expense) => { 
    this.expenses.push(expense) 
    } 

    @computed get getExpense() { 
    if(this.expenses.length > 0) { 
     return `This is computed from ${this.expenses[0] + this.expenses[1]}` 
    } 
    } 
} 

const store = new ExpensesStore() 

autorun(() => { 
    // store.expenses.slice() works just as well 
    console.log(toJS(store.expenses)) 
}) 

reaction(
() => store.expenses.map(expense => expense), expense => console.log(expense) 
) 

setTimeout(() => { 
    store.addExpense(1000) 
}, 1000) 
+1

THX Tholle。我看到我的錯誤考慮console.log。 因此,如果自動運行和反應不需要任何裝飾器,並且可以在類ExpensesStore之外生存,我可以將它們取出,放入其他組件中並從那裏運行它們。有沒有一種方法可以採取行動並計算出來。我想製作一個類似於REDX的結構,我需要在一個文件中執行操作,而在另一個文件中執行操作? –

+0

@ Igor-Vuk沒問題!絕對的,MobX非常靈活。在這種情況下,我會親自保存這些類別的計算結果,但請移動這些行爲。我不久前在一個項目中自己完成了這個任務,並且感覺像一個好的,可變的Redux版本。 – Tholle

+0

我該怎麼做,拿出行動,並從另一個文件調度他們?我提出了另一個問題,如果你想加入。 https://stackoverflow.com/questions/46840028/structure-mobx-project-like-redux 我會接受這個答案作爲我的第一個問題的解決方案。謝謝。 –