XState.js 如何将上下文发送到机器?

XState.js How to send context to a machine?

我是 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()

如何将 ID 传递给上下文?

这并不能解决问题:

      machine.send({ type: 'LOGIN', id })

您必须使用 assign action 来更新上下文。我已将您的示例更新为以下内容:

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

现在调用以下命令:

import { testMachine } from './machines';

const testService = interpret(testMachine).start();
testService.send({type: 'LOGIN', id: 'test' });
//or testService.send('LOGIN', { id: 'test'});


操作 assignId 会将事件中的数据分配给您的上下文