繁体   English   中英

如何跨页面刷新维护React / Redux应用程序的状态?

[英]How to maintain the state of React/Redux application across page refreshes?

我是新来的反应js。

我有两条路线,如A和B.现在我将一些值从A传递给B作为道具。 如果刷新B页面,则A中的所有道具值都将消失,B页面不会呈现。 我正在使用与redux的反应。

mapDispatchToPropsmapStateToProps函数用于将A和B路由之间的值作为props传递。

例如:路由A已完成一些计算并将值存储在redux状态,路由B通过使用mapStateToProps导出为connect(mapStateToProps, mapDispatchToProps)(B) ,其中A的状态值作为props传递给B。

请建议我在上述用例上处理浏览器刷新的最佳方法,以及在路由之间传递值的任何其他最佳方法。 提前致谢。

您的问题涉及两个不同的问题。 首先是在React / Redux应用程序中将props从一个页面传递到另一个页面,其次是在刷新页面时维护应用程序状态。

您已经描述了在基于redux的应用程序中在两个路由之间传递数据的正确方法。

这让我们想到了第二个问题。
刷新页面时如何维护React / Redux应用程序的状态?

当刷新React / Redux应用程序时,它会再次初始化并且redux存储获取它的默认值。

如果您希望跨页刷新或跨不同会话维护应用程序状态,则需要将状态存储在某个位置,并在应用程序初始化时加载它。

我们可以将这个问题分为三个部分:

  • 存储数据的位置
  • 如何存储redux状态
  • 初始化应用程序时如何重新加载数据

让我们分别看一下每个子问题。

存储数据的位置?

您可以使用Web Storage API在用户的浏览器中存储数据。 此API提供了2种存储数据的机制:

  • sessionStorage:只要浏览器处于打开状态,就会保留存储的数据,包括页面重新加载和恢复。
  • localStorage:数据一直保留,直到用户或应用程序清除为止。 即使浏览器已关闭并重新打开,它仍然存在。

sessionStoragelocalStorage都允许您在浏览器中存储键值对,并且两者都提供相同的功能集来管理数据。

对于sessionStorage(从MDN获取的示例):

// Save data to sessionStorage
window.sessionStorage.setItem('key', 'value');

// Get saved data from sessionStorage
var data = window.sessionStorage.getItem('key');

// Remove saved data from sessionStorage
window.sessionStorage.removeItem('key');

// Remove all saved data from sessionStorage
window.sessionStorage.clear();

对于localStorage:

// Save data to localStorage
window.localStorage.setItem('key', 'value');

// Get saved data from localStorage
var data = window.localStorage.getItem('key');

// Remove saved data from localStorage
window.localStorage.removeItem('key');

如何存储redux状态?

您已经知道,Redux提供了一个createStore函数,该函数使用root reducer并返回应用程序store

store对象包含整个应用程序商店,并提供一些方法,包括一个注册监听器的方法。

store.subscribe(listener)可用于向商店添加更改侦听器,每次商店更新时都会调用该更改。

我们将向商店添加一个监听器,它将应用程序状态保存到localStorage

尝试使用createStore在您创建商店的文件中添加:

/**
 * This function accepts the app state, and saves it to localStorage
 * @param state
 */
const saveState = (state) => {
    try {
        // Convert the state to a JSON string 
        const serialisedState = JSON.stringify(state);

        // Save the serialised state to localStorage against the key 'app_state'
        window.localStorage.setItem('app_state', serialisedState);
    } catch (err) {
        // Log errors here, or ignore
    }
};

/**
 * This is where you create the app store
 */
const store = createStore(rootReducer);

/**
 * Add a change listener to the store, and invoke our saveState function defined above.
 */
store.subscribe(() => {
    saveState(store.getState());
});

如何重新加载存储的数据,并在应用程序再次初始化时恢复应用程序状态?

当我们使用createStore创建我们的应用商店时,我们可以选择使用函数的第二个参数将初始状态传递给商店。

当应用程序启动时,我们将检查localStorage是否有任何已保存的数据。 如果我们找到它,我们将把它作为createStore的第二个参数发送。

这样,当应用程序完成初始化时,它将具有与刷新页面或关闭浏览器之前相同的状态。

尝试使用createStore在您创建商店的文件中添加:

/**
 * This function checks if the app state is saved in localStorage
 */
const loadState = () => {
    try {
        // Load the data saved in localStorage, against the key 'app_state'
        const serialisedState = window.localStorage.getItem('app_state');

        // Passing undefined to createStore will result in our app getting the default state
        // If no data is saved, return undefined
        if (!serialisedState) return undefined;

        // De-serialise the saved state, and return it.
        return JSON.parse(serialisedState);
    } catch (err) {
        // Return undefined if localStorage is not available, 
        // or data could not be de-serialised, 
        // or there was some other error
        return undefined;
    }
};

/**
 * This is where you create the app store
 */
const oldState = loadState();
const store = createStore(rootReducer, oldState);

而已! 现在,结合最后两个代码块,您的应用程序可以跨页面刷新维护状态,甚至可以跨浏览器重新启动。

希望这可以帮助。 干杯! :)

你可以尝试redux-persistredux-storage ,当初始化存储createStore(reducer, [preloadedState], [enhancer]) ,你可以获取数据并将其分配给preloadedState

尝试使用react-router ,这将基于route呈现组件。

initialized应用程序时,应用程序应获取数据并使用所需信息更新商店。

例如:在下面的示例中,当IntilizeApp组件正在装载时,计算所需的信息并通过调度操作来更新存储。 使用react的生命周期方法,如componentWillMount来计算。

    import {Router, Route, hashHistory} from 'react-router'
    // import initializeApp
    // import ComponentA
    // import ComponentB

    <Router history={hashHistory}>
      <Route path="/" component={InitializeApp}>
        <Route name="A" path="A" component={ComponentA} />
        <Route name="B" path="B" component={ComponentB} />
      </Route>
    </Router>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM