如何在頁面刷新後保持狀態不變?
P粉384244473
P粉384244473 2024-01-29 08:58:49
0
1
505

大家好,我正在努力尋找一種方法來在頁面刷新後保留我的狀態值。目前,我將值儲存在本機儲存中,我嘗試了許多解決方案來使用戶在頁面重新載入後保持登入狀態仍然無法運作。每次當我刷新頁面時我都會退出,我將非常感謝任何幫助。非常感謝。

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 形式傳回。

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板