English 中文(简体)
用户Austh 显示Osole、MongoDB和网络,但并不能正确保存当地储存
原标题:User Auth showing up in console, MongoDB, & network but not correctly saving to local storage

我担心,一旦用户记录在册或登记册上,我就会正确地储存我的用户数据。 我可以看到,在我的ole子里,用户已经登记/记录成功,新用户储存在我的Mongo。 然而,由于用户Data的储存不正确,因此该网页不应重新浏览,因为它应当放在探索网页上。

When I inspect my application the keys/values are showing the following once a user is logged in/registerred: persist:root --------- {authData: "{"userData":{"loading":false,"error":false,"updateLoading":false,"profile":{}}}",…} authData : "{"userData":{"loading":false,"error":false,"updateLoading":false,"profile":{}}}" _persist : "{"version":-1,"rehydrated":true}"

储存::{>authData”:null,“loading”:false,“error”:true, “updateLoing”:fal ed

* E/CN.6/2009/1。

我的用意是看到分布式阵列中储存的用户数据,并坚持使用:不能是关键。

My files are as follows: ** App.js**

import React from  react ;
import { Routes, Route, Navigate } from  react-router-dom ;
import { useSelector } from  react-redux ;
import  ./App.css ;
import Header from  ./components/Header/Header ;
import UserAuth from  ./pages/Auth/Auth ;
import Explore from  ./pages/Explore/Explore ;
import Profile from  ./pages/Profile/Profile ;
import SearchBar from  ./components/Header/SearchBar/SearchBar ;

function App() {
  const user = useSelector((state) => state.authData.authData);

  return (
    <div className="App">
      <Header />
      <Routes>
        <Route path="/"
          element={user ? <Explore />: <Navigate to="../auth"/>}
        />
        <Route path="/profile/:id"
          element={user ? <Profile/> : <Navigate to="../auth" />} 
        />
        <Route path="/explore" 
        element={user ? <Explore />: <Navigate to="../auth"/>} 
        />
        <Route path="/auth" element={user ? <Navigate to="/explore" />:<UserAuth />} />
        <Route path="/search" element={<SearchBar />} />
      </Routes>
    </div>
  );
}

export default App;

<>Auth.jsx>:

import React, { useState } from "react";
import "./Auth.css";

import { registerUser, loginUser } from  ../../actions/AuthAction 

import { useDispatch, useSelector } from "react-redux";
import { useNavigate } from "react-router-dom";
import Explore from "../Explore/Explore";


const UserAuth = () => {
    const initialState = {
        email:"", username:"",  password:"", confirmpassword:""
    };
    const loading = useSelector((state) => state.authData.loading);
    const navigate = useNavigate();
    const dispatch = useDispatch();
    const [register, setRegister] = useState(false);

    // userData
    const [userData, setUserData] = useState(initialState);

    const [confirmPassword, setConfirmPassword] = useState(true);

    const resetForms=()=>{
        setConfirmPassword(true);
        setUserData(initialState);
    };
    const handleChange = (e)=> { 
        setUserData({...userData, [e.target.name]: e.target.value})
    };

     // Form Submission --
     const handleSubmit = (e) => { 
        setConfirmPassword(true);
        e.preventDefault();
        if (register) { 
          userData.password === userData.confirmpassword
            ? dispatch(registerUser(userData))
            : setConfirmPassword(false); 
        } else {
          dispatch(loginUser(userData));
        }
        navigate("/explore");
      };

      return (
        <div className="UserAuth">      
          <div className="Register-Login">
            <form className="AuthForm" onSubmit={handleSubmit}>
              <h3>{register ? "Register" : "Sign In"}</h3>
      
              {register ? (
                <div className="input-group">
                  <input
                    type="text"
                    placeholder="Email"
                    className="userInput"
                    name="email"
                    value={userData.email}
                    onChange={handleChange}
                  />
                  <input
                    type="text"
                    placeholder="Username"
                    className="userInput"
                    name="username"
                    value={userData.username}
                    onChange={handleChange}
                  />
                </div>
              ) : (
                <div>
                  <input
                    type="text"
                    placeholder="Email"
                    className="userInput"
                    name="email"
                    value={userData.email}
                    onChange={handleChange}
                  />
                </div>
              )}
      
              <div>
                <input
                  type="password"
                  className="userInput"
                  name="password"
                  placeholder="Password"
                  value={userData.password}
                  onChange={handleChange}
                />
                {/* only confirm password if register is true */}
                {register && (
                  <input
                    type="password"
                    className="userInput"
                    name="confirmpassword"
                    placeholder="Confirm Password"
                    value={userData.confirmpassword}
                    onChange={handleChange}
                  />
                )}
              </div>
     
        <span style={{ color: "red", fontSize: "12px", display: confirmPassword ? "none" : "block"}}>
            Passwords Do Not Match
          </span>

        <div className="switch-auth">
          <span style={{fontSize:  20px , textDecoration: "underline", cursor:"pointer"}} 
          onClick={() => {
              resetForms()
              setRegister((prev) => !prev)
              }}>
                {register ? "Already have an account? Click here to login": "Don t have an account? Click here to register"}
          </span>
        </div>

        <button className="register-signup-btn" type="submit" disabled={loading}>
              {loading ? "Loading" : register ? "SignUp" : "Login"}
          </button>
      </form>
    </div>
    </div>
  );
};


export default UserAuth;

<>AuthAction.js:

import * as AuthApi from  ../api/AuthRequest 

// Contain Redux actions related to authentication (loginUser & registerUser) 
// Actions make API calls & dispatch actions to the Redux store with a payload containing the userData

export const loginUser = (formData, navigate) => async(dispatch) => {
    dispatch({type: "AUTH_START"})
    try{
        const {userData} = await AuthApi.loginUser(formData)
        dispatch({type: "AUTH_SUCCESS", userData: userData})
        console.log("Log In Successful");
    }
    catch (error) {
        console.log(error)
        dispatch({type: "AUTH_FAILURE"})
        console.log("Log In Error");
    }
}

export const registerUser = (formData, navigate) => async(dispatch) => {
    dispatch({type: "AUTH_START"})
    try{
        const {userData} = await AuthApi.registerUser(formData)
        dispatch({type: "AUTH_SUCCESS", userData: userData})
        console.log("Register User Successful");
    }
    catch (error) {
        console.log(error)
        dispatch({type: "AUTH_FAILURE"})
        console.log("Register Error");
    }
}

<>ReduxStore.js

import { configureStore } from  @reduxjs/toolkit ;
import { persistStore, persistReducer } from  redux-persist ;
import storage from  redux-persist/lib/storage ;
import { combineReducers } from  redux ;
import thunk from  redux-thunk ;

import authReducer from  ../reducers ;


const rootReducer = combineReducers({
  authData: authReducer
});

const persistConfig = {
  key:  root ,
  storage,
};

const persistedReducer = persistReducer(persistConfig, rootReducer);

export const store = configureStore({
  reducer: persistedReducer,
  middleware: (getDefaultMiddleware) =>
  getDefaultMiddleware({
      serializableCheck: false,
      thunk: true,
  }).concat(thunk),
});

export const persistor = persistStore(store);

<>strong>reducers/index.js:

`import { combineReducers } from "redux";

import AuthReducer from "./AuthReducer";

const rootReducer = combineReducers({
  userData: AuthReducer,
});

export default rootReducer;`

<>AuthReducer.js

const authReducer = (state = { authData: null, loading: false, error: false, updateLoading: false },action) => {
  switch (action.type) {
    case "AUTH_START":
      return {...state, loading: true, error: false };
    case "AUTH_SUCCESS":
      localStorage.setItem("profile", JSON.stringify({...action.userData}));

      return {...state,  authData: action.userData, loading: false, error: false };

    case "AUTH_FAIL":
      return {...state, loading: false, error: true };

    case "UPDATING_START":
      return {...state, updateLoading: true , error: false}
    case "UPDATING_SUCCESS":
      localStorage.setItem("profile", JSON.stringify({...action.userData}));
      return {...state, authData: action.userData, updateLoading: false, error: false}
     
    case "UPDATING_FAIL":
      return {...state, updateLoading: true, error: true}



    case "LOG_OUT":
      localStorage.clear();
      return {...state,  authData: null, loading: false, error: false, updateLoading: false }


    case "FOLLOW_USER":
      return {...state, authData: {...state.authData, user: {...state.authData.user, following: [...state.authData.user.following, action.userData]} }}
    
    case "UNFOLLOW_USER":
      return {...state, authData: {...state.authData, user: {...state.authData.user, following: [...state.authData.user.following.filter((personId)=>personId!==action.userData)]} }}

      default:
      return state;
  }
};

export default authReducer;

<>Index.js

import React from  react ;
import ReactDOM from  react-dom/client ;
import { BrowserRouter } from  react-router-dom ;
import  ./index.css ;
import App from  ./App ;
import { Provider } from  react-redux ;
import { PersistGate } from  redux-persist/integration/react ;
import { store, persistor } from  ./store/ReduxStore ;

const rootElement = document.getElementById( root );
ReactDOM.createRoot(rootElement).render(
  <React.StrictMode>
    <BrowserRouter>
      <Provider store={store}>
        <PersistGate loading={null} persistor={persistor}>
          <App />
        </PersistGate>
      </Provider>
    </BrowserRouter>
  </React.StrictMode>
);

我试图从“奥思行动”档案中解脱,改变我储存的辛迪加和减缩指数。 我确实处于停顿状态,我现在想到,这可能只是一个yn子,或者说我不知道最新情况。 任何反馈都将受到高度赞赏。

问题回答

暂无回答




相关问题
ajax login using httpRequest?

I am trying to develop my login script to give feedback to the user if the login is valid or not. Basically if it isn t correct a div box will show saying its wrong, if its correct it will show its ...

Remotely authenticating client Windows user on demand

Suppose I am writing a server for a particular network protocol. If I know that the client is running on a Windows machine, is it possible for my server to authenticate the Windows user that owns the ...

Role/Permission based forms authorizing/authentication?

While looking into forms authorizing/authentication, I found that it is possible to do role based authorizing by adding an array of roles to a FormsAuthenticationTicket. That way I can write User....

热门标签