集合实用程序 {🚀}
¥Collection utilities {🚀}
它们可以使用相同的通用 API 来操作可观察的数组、对象和映射。这些 API 是完全响应式的,这意味着如果使用 set
添加它们,并使用 values
或 keys
迭代它们,那么 MobX 甚至可以检测到 没有 Proxy
支持 个新属性声明。
¥They enable manipulating observable arrays, objects and Maps with the same generic API.
These APIs are fully reactive, which means that even without Proxy
support new property declarations can be detected by MobX if set
is used to add them, and values
or keys
are used to iterate over them.
values
、keys
和 entries
的另一个好处是它们返回数组而不是迭代器,这使得可以立即对结果调用 .map(fn)
。
¥Another benefit of values
, keys
and entries
is that they return arrays rather than iterators, which makes it possible to, for example, immediately call .map(fn)
on the results.
话虽如此,典型的项目没有理由使用这些 API。
¥All that being said, a typical project has little reason to use these APIs.
使用权:
¥Access:
values(collection)
返回集合中所有值的数组。¥
values(collection)
returns an array of all the values in the collection.keys(collection)
返回集合中所有键的数组。¥
keys(collection)
returns an array of all the keys in the collection.entries(collection)
返回集合中所有[key, value]
对条目的数组。¥
entries(collection)
returns an array of all the entries[key, value]
pairs in the collection.
突变:
¥Mutation:
set(collection, key, value)
或set(collection, { key: value })
使用提供的键/值对更新给定的集合。¥
set(collection, key, value)
orset(collection, { key: value })
update the given collection with the provided key / value pair(s).remove(collection, key)
从集合中删除指定的子项。拼接用于数组。¥
remove(collection, key)
removes the specified child from the collection. Splicing is used for arrays.如果集合具有指定的可观察属性,则
has(collection, key)
返回 true。¥
has(collection, key)
returns true if the collection has the specified observable property.get(collection, key)
返回指定键下的子项。¥
get(collection, key)
returns the child under the specified key.
如果你在不支持 Proxy
的环境中使用访问 API,则还可以使用突变 API,以便它们可以检测到更改。
¥If you use the access APIs in an environment without Proxy
support, then also use the mutation APIs so they can detect the changes.
import { autorun, get, set, observable, values } from "mobx"
const twitterUrls = observable.object({
Joe: "twitter.com/joey"
})
autorun(() => {
// Get can track not yet existing properties.
console.log(get(twitterUrls, "Sara"))
})
autorun(() => {
console.log("All urls: " + values(twitterUrls).join(", "))
})
set(twitterUrls, { Sara: "twitter.com/horsejs" })