我正在try 后,任何用户注册或登录到这个网站的用户将被确认在服务器和响应将被存储在本地存储.根据用户,我会在本地存储中判断用户是否可用,然后登录到站点.当用户新注册并获得服务器响应时,它工作得很好,它节省了本地存储空间,用户可以导航到配置文件.但在我判断同一个用户登录表单后,我收到了来自服务器的响应,但它没有保存在本地存储中,因此我无法判断本地存储中的用户,它也没有导航到配置文件部分.
**这是我的App js文件**
function App() {
const user = useSelector((state) => state.authReducer.authData);
console.log(user);
return (
<div className="App">
<div className="blur" style={{ top: "-18%", right: 0 }}></div>
<div className="blur" style={{ top: "36%", left: "-8rem" }}></div>
<Routes>
<Route
path="/"
element={user ? <Navigate to="home" /> : <Navigate to="auth" />}
/>
<Route
path="/home"
element={user ? <Home /> : <Navigate to="../auth" />}
/>
<Route
path="/auth"
element={user ? <Navigate to="../home" /> : <Auth />}
/>
</Routes>
</div>
auth Reducer file个
state = { authData: null, loading: false, error: false },
action
) => {
switch (action.type) {
case "AUTH_START":
return { ...state, loading: true, error: false };
case "AUTH_SUCCESS":
localStorage.setItem("profile", JSON.stringify({ ...action?.data }));
return { ...state, authData: action.data, loading: false, error: false };
case "AUTH_FAIL":
return { ...state, loading: false, error: true };
default:
return state;
}
};
export default authReducer;
**Index.js文件**
import authReducer from "./AuthReducer";
export const reducers = combineReducers({authReducer})
**Redux存储文件**
legacy_createStore as createStore,
applyMiddleware,
compose,
} from "redux";
import thunk from "redux-thunk";
import { reducers } from "../Reducer";
function saveToLocalStorage(store) {
try {
const serializedStore = JSON.stringify(store);
window.localStorage.setItem("store", serializedStore);
} catch (e) {
console.log(e);
}
}
function loadFromLocalStorage() {
try {
const serializedStore = window.localStorage.getItem("store");
if (serializedStore === null) return undefined;
return JSON.parse(serializedStore);
} catch (e) {
console.log(e);
return undefined;
}
}
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const persistedState = loadFromLocalStorage();
const store = createStore(
reducers,
persistedState,
composeEnhancers(applyMiddleware(thunk))
);
store.subscribe(() => saveToLocalStorage(store.getState()));
export default store;
最后,我在控制台日志(log)中看到一个错误,即
- 操作必须是普通对象.相反,实际的类型是:"promise ".您可能需要在您的store 设置中添加中间件来处理调度其他值,例如‘redux-thunk’来处理调度功能*