【问题标题】:Store in XSTATE for accessing across components?存储在 XSTATE 中以便跨组件访问?
【发布时间】:2020-11-17 12:11:47
【问题描述】:

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

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

【问题讨论】:

    标签: reactjs angular xstate nomachine-nx


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

      无论如何,我不确定您是否已经在 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);

      【讨论】:

        猜你喜欢
        • 2011-02-09
        • 2020-04-16
        • 1970-01-01
        • 2014-06-10
        • 1970-01-01
        • 2013-09-07
        • 1970-01-01
        • 2021-08-02
        相关资源
        最近更新 更多