【问题标题】:Sending data from parent machine to child machine using actors使用actors将数据从父机器发送到子机器
【发布时间】:2020-06-13 01:10:17
【问题描述】:

我试图理解 Actors 能够将数据从兄弟组件传递到另一个组件。

我有这些机器:父母和孩子。 parentMachinesuccess 转换中向childMachine 发送GET 事件。一旦childMachine 收到event.value,就应该在其上下文中将其分配给user 属性。

const [currentChild, sendChild] = useMachine(childMachine);

现在,当我在单击 fetch 后登录 currentChild.context 时,user 属性为空。如何在依赖于childMachine 的组件中使用从parentMachine 接收到的数据?

代码沙盒:https://codesandbox.io/s/patient-frost-9lxoh

const parentMachine = Machine({
  id: "parent",
  initial: "idle",
  context: {
    ref: undefined
  },
  states: {
    idle: {
      on: {
        FETCH: {
          target: "loading"
        }
      }
    },
    loading: {
      invoke: {
        id: "getUser",
        src: (_, event) => fetchUser(event.value),
        onDone: {
          target: "success",
          actions: assign({
            user: (_, event) => {
              return event.data;
            }
          })
        },
        onError: {}
      },
      entry: assign({
        ref: () => spawn(childMachine)
      })
    },
    success: {
      entry: (ctx, evt) => ctx.ref.send({ type: "GET", value: ctx.user })
    },
    failure: {} 
  }
});

const childMachine = Machine(
  {
    id: "child",
    initial: "waitingForData",
    context: {
      user: []
    },
    states: {
      waitingForData: {
        on: {
          GET: {
            actions: [
              assign({
                user: (ctx, evt) => [...ctx.user, evt.value]
              }),
              "logger"
            ]
          }
        }
      }
    }
  },
  {
    actions: {
      logger: ctx => console.log(ctx.user)
    }
  }
);

【问题讨论】:

    标签: xstate


    【解决方案1】:

    为此,您可以调用 Promises、Callbacks、Observables 和 Machines,正如提到的 here,当您调用机器时,您必须等到被调用的机器达到其最终状态,您将在 onDone 中收到结果,当你调用 Promise 时,你必须等到它完成,你也会在 onDone 中收到结果。

    Here you go 调用机器和承诺的示例。

    【讨论】:

      猜你喜欢
      • 2012-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-24
      • 2018-03-22
      • 2020-08-25
      • 2023-01-13
      • 1970-01-01
      相关资源
      最近更新 更多