gpt4 book ai didi

javascript - mobex,@inject 仅商店的特定部分

转载 作者:行者123 更新时间:2023-11-28 13:08:41 25 4
gpt4 key购买 nike

目前我使用的是mobx <Provider store={store} />其中 store 包括所有具有 observables 的 mobx store 类。

在组件内部我使用它访问它

@inject("store")
@observe
class MyComponent ....

但这意味着,如果我只想访问通知存储,我必须 this.props.store.notification.message例如,这会变得非常冗长。有没有办法只获取通知存储?当我们注入(inject)一个字符串"store"时除了对象之外,我看不到一种方法来破坏它。

最佳答案

决定将其作为答案发布,因为它可能对其他人有帮助:

如 mobx-react ( https://github.com/mobxjs/mobx-react ) 的文档所示,Provider 可以接受您传递给它的任何属性,而不仅仅是“stores”。

因此,解决方案是创建一个带有存储的对象,并使用扩展运算符(或任何其他您喜欢的方式)将其传递给 Provider。

const stores = { 
storeOne,
storeTwo,
}

return (
<Provider {...stores}>
<MyComponent />
</Provider>
)

如果您使用 mobx-react 包并想要注入(inject)多个存储 - 只需将存储传递给以逗号分隔的 @inject 函数

@inject('storeOne', 'storeTwo')

我创建了一支笔,其中包含多个商店注入(inject)的示例:https://codepen.io/evgen/pen/NgpVMw

关于javascript - mobex,@inject 仅商店的特定部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44615212/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com