【问题标题】:XState.js How to send context to a machine?XState.js 如何将上下文发送到机器?
【发布时间】:2020-04-23 10:09:11
【问题描述】:

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

【问题讨论】:

    标签: xstate


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2021-12-30
      • 2020-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-15
      相关资源
      最近更新 更多