我试图理解演员能够将数据从兄弟组件传递到另一个组件。
我有这些机器:父母和孩子。在转换中parentMachine
发送一个GET
事件。一旦收到一个它应该被分配给它的上下文中的一个属性。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)
}
}
);