我是React和Mobx的新手,并且正在关注在线教程。
本教程说使用reaction
例如:
reaction(() => list.totalPrice, () => changed++)
但是我只收到错误ReferenceError: reaction is not defined
。
我不确定这意味着什么或如何使它工作(在Google或SO上找不到关于它的任何信息。
根据Mobx文档,我似乎正确地使用了它https://mobx.js.org/refguide/reaction.html
有人知道这意味着什么吗?
我的完整代码是:
import { getSnapshot, onSnapshot, onPatch } from "mobx-state-tree"
import { WishList, WishListItem } from "./WishList"
it("can create a new instance of a model", () => {
const item = WishListItem.create({
name: "some item name",
price: 28.74,
})
expect(item.price).toBe(28.74)
expect(item.image).toBe("")
item.changeName("Narnia")
expect(item.name).toBe("Narnia")
})
it("can create a wishlist", () => {
const list = WishList.create({
items: [
{
name: "another item name",
price: 30.43
}
]
})
expect(list.items.length).toBe(1)
expect(list.items[0].price).toBe(30.43)
})
it("can add new item to list", () => {
const list = WishList.create()
const states = []
onSnapshot(list, snapshot => {
states.push(snapshot)
})
list.add({
name: "A new item",
price: 10
}
)
expect(list.items.length).toBe(1)
expect(list.items[0].name).toBe("A new item")
list.items[0].changeName("Hello world")
expect(list.items[0].name).toBe("Hello world")
expect(getSnapshot(list)).toMatchSnapshot()
expect(states).toMatchSnapshot()
})
// Patches
it("can add new item to list - 2", () => {
const list = WishList.create()
const patches = []
onPatch(list, patch => {
patches.push(patch)
})
list.add({
name: "A new item",
price: 10
}
)
list.items[0].changeName("Hello world 2")
expect(patches).toMatchSnapshot()
})
// Views
it("can calculate the total price of a wishlist", () => {
const list = WishList.create({
items: [
{
name: "Machine gun preacher",
price: 11,
image: ""
},
{
name: "lego",
price: 100,
image: ""
}
]
})
expect(list.totalPrice).toBe(111)
let changed = 0
reaction(() => list.totalPrice, () => changed++)
expect(changed).toBe(0)
console.log(list.totalPrice)
list.items[0].changeName("test")
expect(changed).toBe(0)
list.items[0].changePrice(10)
expect(changed).toBe(1)
})
本教程排除了有关添加的部分
import { reaction } from "mobx"