搜索

首页  >  问答  >  正文

如何在页面刷新后保持状态不变?

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

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粉384244473P粉384244473305 天前500

全部回复(1)我来回复

  • P粉323374878

    P粉3233748782024-01-30 00:40:23

    如果会话持久化到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 形式返回。

    回复
    0
  • 取消回复