4

我是 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 })
4

1 回答 1

5

您必须使用分配操作来更新上下文。我已将您的示例更新为以下内容:

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 mouseService.send('LOGIN', { id: 'test'});


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

于 2020-01-06T12:54:29.427 回答