@muhammad-ali 的回答回答了您的特定问题。当您刷新浏览器时,任何刚刚在内存中的数据/应用程序状态都消失了。您将需要找到其他解决方案来永久保留刷新之间的数据。不过,这与 XState 或 React 无关。由于您的目标似乎是将商品存储在购物车中,因此如果用户返回该站点,他仍然拥有相同的购物车,您将不得不使用localStorage
或使用后端 + 数据存储来永久保存数据并通过以下方式检索数据加载应用程序/购物车页面时的 API。
答案的其余部分与原始问题有点偏离,但可能会提供一些关于机器状态如何使用 XState 机器实际保存在内存中的见解。
机器本身不会持久化状态(甚至在一定程度上不在内存中)。显示这一点的示例是,如果您做一台机器transition
(传入初始状态和您要执行的操作)然后读取机器状态,之后它仍将处于原始状态。XState 机器基本上只是可以执行操作(作为转换)的东西,并且此转换将新状态返回给您。
在问题中使用您的机器:
const cartMachine = Machine({ ... })
const newState1 = cartMachine.transition(cartMachine.initialState, {type: 'ADD', item: {...})
console.log(newState1.context.ItemsInCart) // Will contain item
const newState2 = cartMachine.transition(cartMachine.initialState, {type: 'ADD', item: {...})
console.log(newState2.context.ItemsInCart) // Will still only contain one item (from the last ADD operation)
// can not read the current state from machine, only initialState is available
console.log(cartMachine.initialState.context.ItemsInCart) // will still be []
// You will have to persist state yourself
const newState1 = cartMachine.transition(cartMachine.initialState, {type: 'ADD', item: {...})
// Pass the new state into the machine
const newState2 = cartMachine.transition(newState1, {type: 'ADD', item: {...})
console.log(newState2.context.ItemsInCart) // Will now contain two items
所以机器永远不会保持状态。不过,您有两种选择来实现这一目标。
每次转换后将新状态存储在 React 状态中的某个位置。XState 机器状态是 JSON 可序列化的,因此您可以毫无问题地存储在 React 状态中。
使用机器服务来保持状态(https://xstate.js.org/docs/guides/interpretation.html)。只要您使用该服务的相同实例,每个转换都会持久保存在内存中,直到服务停止。您的机器示例:
import { Machine, assign, interpret } from 'xstate'
const cartMachine = Machine({ ... })
const cartService = interpret(cartMachine)
cartService.start()
cartService.send({type: 'ADD', item: {...})
console.log(cartService.state.context.ItemsInCart) // contains item
cartService.send({type: 'ADD', item: {...})
console.log(cartService.state.context.ItemsInCart) // contains 2 items