【问题标题】:State is changing but transitions are not triggered in Xstate状态正在改变,但 Xstate 中未触发转换
【发布时间】:2021-03-15 21:28:43
【问题描述】:

我正在使用带有 Nextjs 的 xstate。现在我被困在某个地方了。

import { assign, createMachine, interpret } from "xstate";

export interface toggleAuth {
  isAuthenticated: boolean;
  user: {
    name: string | undefined;
  };
}

// console.log(getCachedData());

export const authMachine = createMachine<toggleAuth>({
  id: "auth",
  initial: "unauthenticated",
  context: {
    isAuthenticated: false,
    user: {
      name: undefined,
    },
  },
  states: {
    authenticated: {
      on: {
        toggle: {
          target: "unauthenticated",
        },
      },
      entry: assign({
        user: (ctx) => (ctx.user = { name: "Pranta" }),
        isAuthenticated: (ctx) => (ctx.isAuthenticated = true),
      }),
    },
    unauthenticated: {
      on: {
        toggle: {
          target: "authenticated",
        },
      },
      entry: assign({
        user: (ctx) => (ctx.user = { name: undefined }),
        isAuthenticated: (ctx) => (ctx.isAuthenticated = false),
      }),
    },
  },
});

const service = interpret(authMachine);
service.onTransition((state) => console.log(state));

所以我在看文档。根据他们的说法,每当我从未经身份验证过渡到经过身份验证以及从经过身份验证过渡到未经身份验证时,它都应该在控制台为我记录下来。但事实并非如此。它只做一次。这里发生了什么事。另外,这样定义我的机器可以吗?提前致谢。

【问题讨论】:

    标签: state-machine xstate


    【解决方案1】:

    它没有记录,因为你没有改变状态;从未发送任何事件。

    请重新阅读documentation on assigning to context - 您正在改变上下文而不是分配新值;分配者应该永远是纯粹的。

    如果要查看状态变化,在这种情况下需要发送toggle 事件:

    service.send('toggle');
    

    另外,不需要isAuthenticated;这是多余的,因为该状态由您机器的有限状态 (state.value) 表示。

    【讨论】:

      猜你喜欢
      • 2020-03-14
      • 2015-11-07
      • 2018-08-09
      • 2020-11-06
      • 1970-01-01
      • 2020-02-12
      • 2019-07-04
      • 1970-01-01
      • 2020-02-28
      相关资源
      最近更新 更多