如何在页面刷新后保持状态不变?
P粉384244473
P粉384244473 2024-01-29 08:58:49
0
1
476

大家好,我正在努力寻找一种方法来在页面刷新后保留我的状态值。目前,我将值存储在本地存储中,并且我尝试了许多解决方案来使用户在页面重新加载后保持登录状态仍然不起作用。每次当我刷新页面时我都会退出,我将非常感谢任何帮助。非常感谢。

Core.ts:

class Core {
      agv: typeof agv;
      auth: Auth;
      workflow: WorkflowApi;
      graphql: GraphQLSdk;
      fleetState: Stream<FleetState>;
      taskList: Stream<TaskList>;
      zoneList: Stream<ZoneList>;

  configuration = getConfiguration();

  url: string;

  constructor(options: Options) {
    const auth = getAuth(options);
    const graphqlUrl = `${options.host}/graphql`;
    const graphql = getSdk(new GraphQLClient(graphqlUrl, { fetch: authMiddleware({ auth, fetch: options.fetch }) }));

    const streamContext = {
      ...options,
      headers: getAuthHeaders(auth),
      getSites: () => auth.session.value?.sites || [],
    };

    this.auth = auth;
    this.workflow = getWorkflowApi({ auth }) ;
    this.graphql = graphql;
    this.fleetState = fleetState.call({
      ...options,
      headers: getAuthHeaders(auth),
      getSites: () => auth.session.value?.sites || [],
    });

    this.configuration.map.fetch = this.configuration.map.fetch.bind(async () => {
      const site = auth.session.value.sites[0];
      return graphql.map({ site }).then(({ map }) => map);
    });

    this.taskList = taskList.call(streamContext);
    this.zoneList = zoneList.call(streamContext);

    this.agv = {
      ...agv,
      graphql,
      map: this.configuration.map,
      getSites: () => auth.session.value?.sites || [],
    } as typeof agv;

    auth.session.listen(session => {
      window.localStorage.setItem('session', JSON.stringify(session));
      console.log(session);
      if (session) {
    this.configuration.map.fetch();
      }
    });
  }
}

export { Core };

P粉384244473
P粉384244473

全部回复(1)
P粉323374878

如果会话持久化到localStorage,如下

auth.session.listen(session => {
  window.localStorage.setItem('session', JSON.stringify(session));
  ...
})

那么我认为你可以从getAuth中的localStorage进行初始化,如下所示

function getAuth({ host, fetch }: Dependencies) {
  const session = getEventEmitter({
    initialValue: JSON.parse(window.localStorage.getItem("session")),
  });

  ...

如果没有会话保持在状态,则 null 是表达式的值,并以 initialValue 形式返回。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!