使用角色将数据从父计算机发送到子计算机

时间:2020-02-28 22:25:53

标签: xstate

我试图了解Actor能够将数据从同级组件传递到另一个组件。

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

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)
    }
  }
);

0 个答案:

没有答案