English 中文(简体)
A. 使用国 JS not Update the Object within Provider - In multi Layouts
原标题:useState in ReactJS not updating the object inside Context Provider - In multiple Layouts

我的认证背景提供者如下。 我在成功认证用户时确定了一些象征性的价值。

import axios from "axios";
import { createContext, useContext, useState } from "react";
import Constants from "../common/Constants";
import Payload from "../classes/Payload";

const AuthenticationContext = createContext({
    loggedUserToken: {},
    session: {}
});

export const useAuthenticationStatus = () => useContext(AuthenticationContext);

const AuthenticationContextProvider = ({children}) => {

    const [loggedUserToken, setLoggedUserToken]     = useState({});
    const [session, setSession]                     = useState({});


    const authenticateUser = async (loginEndpoint, email, userPassword) => {         

        let result                                  = {};
        let statusCode                              = -1;
        let statusText                              =   ;
        let message                                 =   ;
        let session                                 =   ;
        let postData                                = {username: email, password: userPassword};

        await axios.post(loginEndpoint, postData, {headers: headerData})
                .then( data => {

                    statusCode                      = data.data.code;
                    statusText                      = data.data.statusText;
                    session                         = data.data.session;
                    message                         = data.data.message;

                    if (statusCode === 200) {                

                        let challengeName           = message.challengeName;
                        let payloadData             =   ;
                        
                        if (session !== null && message.challenge !== null) {

                            let userEmail           = message.userEmail;
                            setSession({ sD : session,  sE : userEmail });
                            
                            if (challengeName === Constants.COGNITO_CHALLENGE_NEW_PASSWORD_REQUIRED ) {
                                statusText          = Constants.AUTHENTICATION_SET_NEW_PASSWSORD;
                                payloadData         = challengeName;
                            }

                            result = {  s : true,  sT : statusText,  p : payloadData};

                        } else {
                            statusText              = Constants.AUTHENTICATION_LOGIN_SUCCESSFUL;
                            payloadData             = message;

                            let userpayloadData      = new Payload(payloadData);

                            //set use state for user token - ERROR IN HERE
                            //loggedUserToken IS NOT SET HERE
                            setLoggedUserToken(loggedUserToken => userpayloadData);

                            result = {  s : true,  sT : statusText,  p : payloadData};

                        }                        

                    }

                }).catch( error => {
                    
                    result = {  s : false,  sT : Constants.COMMON_ERROR_MESSAGE,  p :   };

                });

        return result;  
    }

    

    return (
        <AuthenticationContext.Provider
            value={{loggedUserToken, authenticateUser, session, setPermanentPassword}}>
            {children}
        </AuthenticationContext.Provider>
    )
};

export default AuthenticationContextProvider;

我在家中使用了“超标的User Token”值,以检查其有无。

import { useEffect } from "react";
import { useAuthenticationStatus } from "../../services/AuthenticateContextProvider";

function HomeView() {

    const {loggedUserToken} = useAuthenticationStatus();
    
    //empty object output
    console.log(loggedUserToken);

    useEffect( () => {
        //empty object output
        console.log(loggedUserToken);
    })

    return (

        
        <div className="col-12">
            
            <div className="row mt-2">
                <div className="col-12">

                </div>
            </div>

            <div className="row mt-5 incident-list-map">

                <div className="col-md-4">

                    <h2>List</h2>
                    
                    <div></div>

                </div>

                <div className="col-md-8">
                    <div id="map" className="map">
                        
                    </div>

                </div>

            </div>

        </div>

    );
}

export default HomeView;

即使你将其归入认证提供者,“挂号为User Token”总是空洞的(即使你在“LobedUser Token”之后将它排在认证提供者手中)。 在适当确定“企业”的情况下,我从不同的角度看待这一价值。

I am not sure what is going wrong in here

UPDATE: below is how I use the authentication provider. The "Outlet" replaces the different views in the MainLayout.

import { Outlet } from "react-router-dom";
import MainHeader from "../common/MainHeader";
import MainFooter from "../common/MainFooter";
import AuthenticationContextProvider from "../../services/AuthenticateContextProvider";

function MainLayout() {

    return(

        <div className="main-layout">
            <AuthenticationContextProvider>
                <header>
                    <nav className="navbar navbar-expand-md fixed-top header-area">
                        <MainHeader></MainHeader>
                    </nav>
                </header>
                
                <main className="flex-shrink-0 main-area">
                    <div className="container-fluid">
                        <div className="main-content">
                            
                                <Outlet />
                            
                        </div>
                        
                    </div>
                </main>

                <footer className="footer mt-auto py-3 footer-content">
                    <div className="container-fluid">
                        <MainFooter></MainFooter>
                    </div>
                </footer>
            </AuthenticationContextProvider>
        </div>

    );

}

export default MainLayout;
问题回答

我已经指出了这一点。 上述错误是由于我所用的布局所致。 我用一个布局来验证观点(如标识、登记等)和其他观点(家庭、与我们联系等)。

And I have encapsulated those with the authentication context provider separately. Like below;

import { Outlet } from "react-router-dom";
import MainHeader from "../common/MainHeader";
import MainFooter from "../common/MainFooter";
import AuthenticationContextProvider from "../../services/AuthenticateContextProvider";

function MainLayout() {

    return(

        <div className="main-layout">
            <AuthenticationContextProvider>
                <header>
                    <nav className="navbar navbar-expand-md fixed-top header-area">
                        <MainHeader></MainHeader>
                    </nav>
                </header>
                
                <main className="flex-shrink-0 main-area">
                    <div className="container-fluid">
                        <div className="main-content">
                            
                                <Outlet />
                            
                        </div>
                        
                    </div>
                </main>

                <footer className="footer mt-auto py-3 footer-content">
                    <div className="container-fluid">
                        <MainFooter></MainFooter>
                    </div>
                </footer>
            </AuthenticationContextProvider>
        </div>

    );

}

export default MainLayout;

import { Outlet } from "react-router-dom";
import MainHeader from "../common/MainHeader";
import MainFooter from "../common/MainFooter";
import AuthenticationContextProvider from "../../services/AuthenticateContextProvider";

function MainLayout() {


    return(

        <div className="main-layout">
            
                <header>
                    <nav className="navbar navbar-expand-md fixed-top header-area">
                        <MainHeader></MainHeader>
                    </nav>
                </header>
                
                <main className="flex-shrink-0 main-area">
                    <div className="container-fluid">
                        <div className="main-content">
                            
                                <Outlet />
                            
                        </div>
                        
                    </div>
                </main>

                <footer className="footer mt-auto py-3 footer-content">
                    <div className="container-fluid">
                        <MainFooter></MainFooter>
                    </div>
                </footer>

        </div>

    );

}

export default MainLayout;

但是,当我把认证背景提供人移到下文所述的申请人时,他就发挥了作用。 在我的理解中,我认为是在从认证布局移至主要布局时发生的,认证的背景提供商正在重新确定(其实物是主要布局的单独背景提供人)。 但是,由于我把环境提供者移至顶端(App.js),现在所有的布局都很常见。

import  bootstrap/dist/css/bootstrap.css ;
import  bootstrap/dist/js/bootstrap.js ;
import  ./App.css ;
import { Route, Routes } from  react-router-dom ;
import AuthenticationLayout from  ./components/layouts/AuthenticationLayout ;
import LoginView from  ./components/authentication/LoginView ;
import ForgotPasswordView from  ./components/authentication/ForgotPasswordView ;
import MainLayout from  ./components/layouts/MainLayout ;
import HomeView from  ./components/main/HomeView ;
import ConfirmEmailView from  ./components/authentication/ConfirmEmailView ;
import SetNewPassword from  ./components/authentication/SetNewPassword ;
import AuthenticationContextProvider from  ./services/AuthenticateContextProvider ;

function App() {

  return (

    <>
      <AuthenticationContextProvider>
        <Routes>
          <Route element={ <AuthenticationLayout /> }>
            <Route path= /  element={ <LoginView /> }></Route>
            <Route path= /login  element={ <LoginView /> }></Route>
            <Route path= /forgotpassword  element={ <ForgotPasswordView />}></Route>
            <Route path= /confirmemail element={ <ConfirmEmailView /> }></Route>
            <Route path= /setnewpassword  element={ <SetNewPassword /> }></Route>
          </Route>

          <Route element={ <MainLayout /> }>
            <Route path= /home  element={ <HomeView /> }></Route>
          </Route>

        </Routes>
      </AuthenticationContextProvider>
    </>

  );

}

export default App;




相关问题
How to use one react app into another react app?

I have two react apps, parent app and child app. and child app have an hash router. I have build the child app using npm run build, It creates build folder. That build folder moved into inside the ...

how to get selected value in Ant Design

I want to print the selected value, and below is my option list: const vesselName = [ { value: 0 , label: ALBIDDA , }, { value: 1 , label: ALRUMEILA , }, { value: 2 ,...

How to add a <br> tag in reactjs between two strings?

I am using react. I want to add a line break <br> between strings No results and Please try another search term. . I have tried No results.<br>Please try another search term. but ...

热门标签