【发布时间】:2018-03-25 20:18:58
【问题描述】:
我在玩 mobx-state-tree 并试图找出将 window.innerHeight 之类的东西绑定到我的商店的最佳方法。我对Mobx 完全陌生,所以我无法立即想象如何使用observer()(或其他相关方法)来集成它。在docs 中纯粹使用Mobx 似乎有一些很好的信息,但我想知道mobx-state-tree 的推荐内容。
据我所知,我可以从使用getEnv() 获取window 开始,遵循dependency injection 的文档:
Example.js
import { types, getEnv } from "mobx-state-tree"
const Box = types.model({
width: types.number,
height: types.number
})
.actions(self => ({
setWidth() {
const width = getEnv(self).window.innerWidth
self.width = width / 10
}
}))
export default Box
测试文件
import {Box} from './Example'
//mock window for testing
const window = {
innerWidth: 1200
}
const store = Box.create({
width: 100,
height: 100
}, {
window: window /* inject window into store */
}
)
//Test
it('updates from window width', () => {
store.setWidth()
expect(store.width).toBe(120)
})
这在我在测试套件中运行时有效。
我将如何编写它以便window.innerWidth 随时更改Box 将重新计算其宽度?也许我可以使用views,并让Box 成为代表更改的更大UI 存储的子节点?
任何建议都将不胜感激,并提前致谢!
【问题讨论】:
标签: user-interface mobx observers mobx-react mobx-state-tree