我试图理解Actors能够将数据从同级组件传递到另一个组件。
我有这样的机器:父母和孩子。parentMachine
在GET
转换中向childMachine
发送一个success
事件。一旦childMachine
接收到event.value
,就应该在其上下文中将其分配给user
属性。
const [currentChild, sendChild] = useMachine(childMachine);
现在,在单击fetch后记录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)
}
}
);
https://stackoverflow.com/questions/60460041
复制相似问题