0

我有组件 A 和组件 B,在组件 A 中进行一些选择后,组件 B 应该能够获得更新状态或选择。我已经分别为 MachineA 和 MachineB 分配了单独的机器。我想知道如何在组件 B 中获取 MachineB 的上下文,该上下文在组件 A 中得到更新。

例如:组件 A 从机器 A 获取数据并使用所选产品更新机器 B 的上下文。现在组件 B 应该能够访问已更新的机器 B 的存储。知道怎么做吗?我不想将状态作为道具传递。

4

2 回答 2

4

提升状态,并使用context。将两台机器放在上下文中,以便所有组件共享相同的机器实例。

于 2020-08-04T13:17:38.073 回答
0

你应该提供一些代码,你正在使用reactjsangular标签,所以很难知道你的代码有什么。

无论如何,我不确定您是否已经在 A 机器内调用 B 机器,这是连接它们的第一步。第二步是在组件 B 上使用 B 机器,但来自 A 机器。在反应将是这样的

// A machine file
const AMachine = Machine({
  id: "aState",
  initial: "initialState",
  invoke: [
    { id: "bState", src: BMachine }
  ],
  states: {...},
}


// A component
const [state, send] = useMachine(AMachine);
const AMachineContext = React.createContext(null);

<AMachineContext.Provider value={state}>
  <BComponent />
</AMachineContext.Provider>


// B component
const aMachine = useContext(AMachineContext);
const [bState] = useService(aMachine.children.bState);

于 2020-12-04T16:41:20.270 回答