面试题答案
一键面试技术方案选择
可以使用 localStorage
来实现路由状态的数据持久化。localStorage
能够在浏览器端持久化存储简单的数据,并且使用起来较为方便。
与 Redux 工作流程相结合的方式
- 在 Redux store 创建时从 localStorage 中读取数据:在应用启动时,从
localStorage
中读取之前保存的路由状态,并将其作为初始状态的一部分传入 Redux store。 - 在路由状态变化时更新 localStorage:当路由状态在 Redux 中通过 action 和 reducer 更新时,同步将新的路由状态保存到
localStorage
中。
代码片段
- 在 Redux store 创建时读取 localStorage 数据
import { createStore } from 'redux';
import rootReducer from './reducers';
// 从localStorage读取路由状态
const persistedState = localStorage.getItem('routeState')
? JSON.parse(localStorage.getItem('routeState'))
: {};
const store = createStore(rootReducer, persistedState);
export default store;
- 在 reducer 中更新 localStorage
假设我们有一个处理路由状态的 reducer,例如
routeReducer
:
const initialState = {
currentRoute: '/'
};
const routeReducer = (state = initialState, action) => {
switch (action.type) {
case 'UPDATE_ROUTE':
const newState = {
...state,
currentRoute: action.payload
};
// 更新localStorage
localStorage.setItem('routeState', JSON.stringify(newState));
return newState;
default:
return state;
}
};
export default routeReducer;
- 触发路由状态更新的 action 创建函数
const updateRoute = (route) => {
return {
type: 'UPDATE_ROUTE',
payload: route
};
};
export { updateRoute };
- 在 React 组件中使用 action 更新路由状态
import React from'react';
import { useDispatch } from'react-redux';
import { updateRoute } from './actions';
const MyComponent = () => {
const dispatch = useDispatch();
const handleRouteChange = (newRoute) => {
dispatch(updateRoute(newRoute));
};
return (
<div>
{/* 模拟路由切换 */}
<button onClick={() => handleRouteChange('/new-route')}>切换路由</button>
</div>
);
};
export default MyComponent;
通过以上步骤,就可以实现路由状态在刷新页面后能恢复到刷新前的状态。如果数据量较大或需要更复杂的存储结构,也可以考虑使用 IndexedDB
,其操作方式类似,但 API 更复杂且功能更强大。