簡體   English   中英

setState()是可選的,用於更新Alt.js存儲中的狀態嗎?

[英]Is setState() optional for updating the state in Alt.js store?

是的,我知道setState()更新商店的狀態並向所有訂閱者發出更改事件 ,但是我發現並不是每個人都使用它並在更新狀態時忽略它。

例如,在以下alt-todo repo中 ,它們不使用setState()

class TodoStore {
    constructor() {
        this.bindActions(TodoActions);

        this.todos = {};
    }

    onCreate(text) {
        text = text.trim()
        if (text === '') {
            return false
        }
        // hand waving of course.
        const id = (+new Date() + Math.floor(Math.random() * 999999)).toString(36)
        this.todos[id] = {
            id: id,
            complete: false,
            text: text
        }
    }
}

但是,在官方的alt.js存儲庫中,他們使用它:

class LocationStore {
    constructor() {
        this.bindAction(locationActions.updateLocation, this.onUpdateLocation);

      this.state = {
        city: 'Denver',
        country: 'US'
      };
    }

    onUpdateLocation(obj) {
        const { city, country } = obj
        this.setState({ city, country });
    }
}

所以我想知道這兩種方式有什么區別?

真的沒有:

setState由Alt內部使用以設置狀態。 您可以重寫此方法以提供自己的setState實現。 在內部,setState是Object.assign的別名。 setState必須返回一個對象。

http://alt.js.org/docs/createStore/#setstate

一個例子:假設您的狀態是:

{
  city: 'Denver',
  country: 'US',
}

更新狀態的兩種方式:

this.setState({city: 'Colorado Springs'})
console.log(this.state) // {city: 'Colorado Springs', country: 'US' })

this.state = { city: 'Elbert' }
console.log(this.state) // state is {city: 'Elbert'}

如您所見, this.state =覆蓋狀態,而this.setState()將新狀態合並為舊狀態。 參見Object.assign()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM