Javascript 如何跨页面刷新维护React/Redux应用程序的状态?
我是新手 我有两条类似A和B的路线。现在我将一些值作为道具从A传递到B。如果刷新了B页,则A中的所有道具值都将消失,并且B页不会呈现。我正在使用react with reduxJavascript 如何跨页面刷新维护React/Redux应用程序的状态?,javascript,reactjs,react-router,react-redux,Javascript,Reactjs,React Router,React Redux,我是新手 我有两条类似A和B的路线。现在我将一些值作为道具从A传递到B。如果刷新了B页,则A中的所有道具值都将消失,并且B页不会呈现。我正在使用react with redux mapDispatchToProps&mapStateToProps函数用于在A&B路由之间作为道具传递值 例如:路线A已经完成了一些计算并将值存储在redux状态,路线B通过使用MapStateTrops导出为connect(MapStateTrops,mapDispatchToProps)(B),其中A的状态值作为道
mapDispatchToProps
&mapStateToProps
函数用于在A&B路由之间作为道具传递值
例如:路线A已经完成了一些计算并将值存储在redux状态,路线B通过使用MapStateTrops
导出为connect(MapStateTrops,mapDispatchToProps)(B)
,其中A的状态值作为道具传递给B
请就上述用例向我建议处理浏览器刷新的最佳方法,以及在路由之间传递值的其他最佳方法。提前感谢。尝试使用
react router
,这将基于路由呈现组件
当应用程序初始化时,应用程序应获取数据并用所需信息更新存储
例如:在下面的示例中,当initializeapp
组件装载时,计算所需的信息并通过调度操作更新存储。使用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>
从'react Router'导入{Router,Route,hashHistory}
//导入初始化EAPP
//进口组件a
//进口组件B
您可以尝试redux-persist
或redux-storage
,
初始化存储时
createStore(reducer、[prepreadedstate]、[enhancer])
,
您可以获取数据并将其分配到PreviedState您的问题涉及两个不同的问题。第一个是在React/Redux应用程序中将道具从一个页面传递到另一个页面,第二个是在页面刷新时维护应用程序状态
您已经描述了在基于redux的应用程序中在两条路由之间传递数据的正确方法
这就引出了第二个问题。
刷新页面时如何保持React/Redux应用程序的状态?
当React/Redux应用程序刷新时,它将再次初始化,并且Redux存储将获取其默认值
如果您希望跨页面刷新或跨不同会话保持应用程序状态,则需要将状态存储在某个位置,并在应用程序初始化时加载
我们可以把这个问题分为三个部分:
- 在哪里存储数据
- 如何存储redux状态
- 初始化应用程序时如何重新加载数据
让我们分别来看每个子问题
数据存储在哪里?
可以使用在用户浏览器中存储数据。此API提供了两种存储数据的机制:
- 会话存储:只要浏览器处于打开状态,存储的数据就会被保留,包括页面重新加载和恢复
- localStorage:数据被保留,直到用户或应用程序清除为止。即使浏览器关闭并重新打开,它也会持续存在
和都允许您在浏览器中存储键值对,并且都提供相同的功能集来管理数据
对于会话存储(示例取自MDN):
对于本地存储:
// 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
函数,它接受我们的根减缩器并返回应用程序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());
});
/**
* 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);
再次初始化应用程序时,如何重新加载存储的数据并恢复应用程序状态?
当我们使用createStore
创建应用商店时,我们可以选择使用函数的第二个参数将初始状态传递给商店
当应用程序启动时,我们将检查localStorage
中是否有任何保存的数据。如果找到它,我们将把它作为第二个参数发送到createStore
这样,当应用程序完成初始化时,它将具有与刷新页面或关闭浏览器之前相同的状态
尝试使用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());
});
/**
* 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);
就这样!现在,结合最后两段代码,您的应用程序就能够在页面刷新甚至浏览器重新启动时保持状态
希望这有帮助。
干杯
:)例如,将值保留在location.query中。向我们展示在刷新过程中如何将值从A传递到B您的redux状态丢失。您需要在sessionStorage
中存储所需的值,并在storeCreation
@Panther期间将其还原,谢谢。这正是我正在做的。一切正常。但是我做的方式在我看来很糟糕。这就是我在这里寻求帮助的原因。目前我正在检查道具中是否有值,如果道具中没有值,那么我将从sessionStorage获取值。这是正确的吗?因为如果有很多地方使用道具,那么我需要在所有地方进行检查。如果您与大家分享任何示例,都会很有帮助。您需要在storeCreation
期间检查会话存储,而不是每次加载组件时都检查会话存储。从会话存储中检索所需的值并存储在