Reactjs 检查用户是否在打开网站时登录的最佳方法
我有一个react应用程序,它使用RESTAPI与express服务器进行会话。Reactjs 检查用户是否在打开网站时登录的最佳方法,reactjs,rest,express,http,redux,Reactjs,Rest,Express,Http,Redux,我有一个react应用程序,它使用RESTAPI与express服务器进行会话。 在我的Redux商店(在前端)中,我将“isLoggedIn”存储在Redux状态。基于该属性,我显示登录页面或主页。现在,当我打开网站时,初始的redux“isLoggedIn”状态为false,所以问题是,如何检查用户是否实际登录。我正在考虑向端点发送请求,以获取主页中所需的数据,如果用户未登录,我将得到401响应,然后显示登录页面。这是正确的方法吗?在我讨论如何保持redux状态之前,我建议您(注意这是个人观
在我的Redux商店(在前端)中,我将“isLoggedIn”存储在Redux状态。基于该属性,我显示登录页面或主页。现在,当我打开网站时,初始的redux“isLoggedIn”状态为false,所以问题是,如何检查用户是否实际登录。我正在考虑向端点发送请求,以获取主页中所需的数据,如果用户未登录,我将得到401响应,然后显示登录页面。这是正确的方法吗?在我讨论如何保持redux状态之前,我建议您(注意这是个人观点)
persistReducer
传递给persistStore函数,该函数将确保redux状态保持不变
下面的实施
import { createStore } from 'redux';
import { persistStore, persistReducer } from 'redux-persist';
import storage from 'redux-persist/lib/storage';
import autoMergeLevel2 from 'redux-persist/lib/stateReconciler/autoMergeLevel2';
import rootReducer from './reducers';
//Import above comes from a file **reducers** which has the combineReducers
// basically based on this code snippet
// I have my combineReducer object in another folder hope that it
//makes sense. Avoided to write it here to keep code short to show
//more of setup in store persisiting
const persistStoreConfigs = {
key: 'root',
storage: myAppStorage,
stateReconciler: autoMergeLevel2
};
const persistantReducer = persistReducer(persistStoreConfigs, rootReducer);
export const store = createStore(persistantReducer);
export const persistor = persistStore(store);
现在将商店传递到应用程序级别
import React from 'react';
import { Provider } from 'react-redux';
import { PersistGate } from 'redux-persist/lib/integration/react';
// This are coming from the store code above that we made
import { persistor, store } from './store';
// This are basically your Custom Componentd
import { HomePage, LoadingView } from './components';
const App = () => {
return (
<Provider store={store}>
// the loading and persistor props are both required!
// Noting that the LoadingView is a custom component
// But the persistor isn't
//The main aim of this two props is to delay the rendering of your app UI until the persited state is retrieved hence the loading screen component
<PersistGate loading={<LoadingView />} persistor={persistor}>
<HomePage />
</PersistGate>
</Provider>
);
};
export default App;
从“React”导入React;
从'react redux'导入{Provider};
从'redux persist/lib/integration/react'导入{PersistGate};
//这是我们制作的上面的商店代码
从“/store”导入{persistor,store};
//这基本上是您的自定义组件
从“/components”导入{HomePage,LoadingView};
常量应用=()=>{
返回(
//加载和persistor道具都是必需的!
//注意,LoadingView是一个自定义组件
//但坚持者不是
//这两个道具的主要目的是延迟应用程序UI的呈现,直到检索到分散状态,从而加载屏幕组件
);
};
导出默认应用程序;