1

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

我有这些机器:父母和孩子。在转换中parentMachine发送一个GET事件。一旦收到一个它应该被分配给它的上下文中的一个属性。childMachinesuccesschildMachineevent.valueuser

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

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

CodeSandbox: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)
    }
  }
);
4

1 回答 1

0

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

这是一个调用机器和承诺的例子。

于 2021-12-09T17:41:38.203 回答