我正在使用xstate和Nextjs。现在我被困在某个地方了。
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));所以我在看文件。根据他们的说法,每当我从未验证转换到已验证,再从已验证转换到未验证时,它都应该为我记录日志。但事实并非如此,它只发生了一次。这里发生了什么。另外,可以这样定义我的机器吗?提前谢谢。
发布于 2020-12-04 22:30:54
它不会记录日志,因为您没有更改状态;没有发送任何事件。
请重新阅读documentation on assigning to context -您正在改变上下文,而不是分配新值;分配者应该始终是纯的。
如果你想看到状态的改变,你需要发送一个toggle事件:
service.send('toggle');此外,不需要isAuthenticated;这是多余的,因为该状态由计算机的有限状态(state.value)表示。
https://stackoverflow.com/questions/65133199
复制相似问题