如何使用React呈现用户以前的会话?

问题描述 投票:0回答:2

我正在使用React js构建一个webapp,它允许用户添加文本,更改文本,添加图像,更改图像以及上传自己的图像。

我希望能够在页面关闭选项卡或转到其他页面时重新加载页面。我知道我可以使用localStorage存储,但是当我们返回到该页面时,我无法呈现它。如何将localStorage注入到正文中以便呈现该会话?

我正在使用MERN堆栈来处理用户数据。但在这种情况下,我不一定要存储页面的JSON字符串表示。我只想将它保存在浏览器的本地存储中,并在用户离开之前渲染元素(位置,尺寸等)。

javascript reactjs web local-storage
2个回答
0
投票

也许是这样的?

localState.js

export const clearState = () => {
  localStorage.removeItem('state');
}

export const loadState = () => {
  try {
    const state = localStorage.getItem('state');
    if (state === null) {
      return {};
    }

    return JSON.parse(state)
  } catch (err) {
    console.warn('%c load state error', 'color: #b00', err);
  }
};

export const saveState = (state) => {
  try {
    localStorage.setItem('state', JSON.stringify(state));
  } catch (err) {
    console.warn('%c save state error', 'color: #b00', err);
  }
};

index.js

import { createStore } from 'redux';
import { composeWithDevTools } from 'redux-devtools-extension';
import reducers from './reducers.js';
import { clearState, loadState, saveState} from './localState.js';

const initialState = loadState();

const store = createStore(
  reducers,
  initialState,
  composeWithDevTools(applyMiddleware(...middlewares)), // not necessary, but nice for debugging
);

// save the state whenever the Redux store changes
store.subscribe(() => {
  const state = store.getState();
  if (state.user.signOut) {
    clearState();
  } else {
    saveState(store.getState());
  }
});

ReactDOM.render(
  <AppRoot store={store} />,
  document.getElementById('root')
);

需要注意的是,如果您更改了架构,则需要将已保存的状态吹走以避免出现奇怪的错误。或者您可以使用架构版本控制。


0
投票

如果您希望Web应用程序显示用户数据,则需要使用某种数据库。 MySQL和PostgreSQL是很棒的SQL数据库。如果你从来没有使用过SQL数据库,那么MySQL就可以开始了。如果您不想使用SQL数据库,则可以使用NoSQL数据库,该数据库使用.json文件来表示您的数据。有一些工具可以帮助您管理.json数据文件,如mongoDB。请注意,如果您计划扩展此应用程序,那么非常大的SQL数据库会更好,因为NoSQL数据库更适合原型设计。

此外,您还需要一个托管服务器来下载这些数据库,并将您的内容提供给公共网站。有许多云托管服务提供商,如亚马逊网络服务,微软Azure,谷歌云,数字海洋和Linode,仅举几个更受欢迎的。

© www.soinside.com 2019 - 2024. All rights reserved.