状态正在改变,但在 Xstate 中未触发转换
State is changing but transitions are not triggered in Xstate
我正在使用带有 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));
所以我在看文档。根据他们的说法,每当我从未经身份验证过渡到经过身份验证以及经过身份验证过渡到未经身份验证时,它都应该为我进行控制台记录。但事实并非如此。它只做一次。这里发生了什么事。另外,这样定义我的机器可以吗?提前致谢。
它没有记录,因为你没有改变状态;从未发送任何事件。
请重新阅读 documentation on assigning to context
- 您正在改变上下文而不是分配新值;分配者应该始终是纯的。
如果你想看到状态变化,你需要在这种情况下发送一个toggle
事件:
service.send('toggle');
另外,也不需要isAuthenticated
;这是多余的,因为该状态由您机器的有限状态 (state.value
) 表示。
我正在使用带有 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));
所以我在看文档。根据他们的说法,每当我从未经身份验证过渡到经过身份验证以及经过身份验证过渡到未经身份验证时,它都应该为我进行控制台记录。但事实并非如此。它只做一次。这里发生了什么事。另外,这样定义我的机器可以吗?提前致谢。
它没有记录,因为你没有改变状态;从未发送任何事件。
请重新阅读 documentation on assigning to context
- 您正在改变上下文而不是分配新值;分配者应该始终是纯的。
如果你想看到状态变化,你需要在这种情况下发送一个toggle
事件:
service.send('toggle');
另外,也不需要isAuthenticated
;这是多余的,因为该状态由您机器的有限状态 (state.value
) 表示。