我是 XState.js 的新手。
我想在我的上下文中使用一个简单的 ID。如何使用 更新上下文machine.send()?
const fetchMachine = Machine(
{
id: 'test',
initial: 'init',
context: {
id: '',
},
states: {
init: {
on: {
LOGIN: 'fetch',
},
},
fetch: {
on: {
LOGOUT: 'init',
},
},
}
})
const machine = interpret(fetchMachine).start()
Run Code Online (Sandbox Code Playgroud)
如何将 ID 传递给上下文?
这不能解决问题:
machine.send({ type: 'LOGIN', id })
Run Code Online (Sandbox Code Playgroud)
您必须使用分配操作来更新上下文。我已将您的示例更新为以下内容:
import { Machine, assign } from 'xstate';
// Action to assign the context id
const assignId = assign({
id: (context, event) => event.id
});
export const testMachine = Machine(
{
id: 'test',
initial: 'init',
context: {
id: '',
},
states: {
init: {
on: {
LOGIN: {
target: 'fetch',
actions: [
assignId
]
}
},
},
fetch: {
on: {
LOGOUT: 'init',
},
},
}
},
{
actions: { assignId }
}
);
Run Code Online (Sandbox Code Playgroud)
现在一旦你调用以下内容:
import { testMachine } from './machines';
const testService = interpret(testMachine).start();
testService.send({type: 'LOGIN', id: 'test' });
//or mouseService.send('LOGIN', { id: 'test'});
Run Code Online (Sandbox Code Playgroud)
该操作assignId会将事件中的数据分配给您的上下文
| 归档时间: |
|
| 查看次数: |
1160 次 |
| 最近记录: |