首页 > 解决方案 > 身份验证后传递后端数据以在 React JS 中呈现到屏幕?

问题描述

请注意,您无需浏览所有代码,我已添加它们以供参考。

我有一个登录屏幕,可以从后端数据验证用户的详细信息。我使用了一个可重用的Auth.jsx组件来初始化和进行身份验证:

    class Auth
    {
        constructor()
        {
            this.authenticated = false;
        }
        login(props)
        {
            this.authenticated = true;
            alert(props);
        }
        logout(cb)
        {
            this.authenticated = false;
        }
        isAuthenticated()
        {
            return this.authenticated;
        }
    
    }

export default new Auth();

这是我的登录中触发功能的代码,用于后端验证,您可以忽略其余代码,直接提交按钮回调

import React, { useState } from "react";
import Form from 'react-bootstrap/Form';
import Button from 'react-bootstrap/Button';
import ErrorCodes from '../constants/ErrorCodes.jsx';
import LoginDetails from '../constants/LoginDetails.jsx';
import Auth from '../security/Auth.jsx';
export default function LoginScreen(props)
{
  const [credentials,setCredentials] = useState({
    email:"",
    password:""
  });
  const [credentialMessage,setcredentialMessage]=useState({
    email:"",
    password:""
  });
  function ErrorChecker()
  {
    let regex = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
    if(regex.test(credentials["email"]))
      setcredentialMessage({...credentialMessage, ["email"]: ErrorCodes[0]});
 
    else
      setcredentialMessage({...credentialMessage, ["email"]: ErrorCodes[4]});

  }
  function LoginScreenRenderer(props)
  {
    return <Form.Group key={props.id} autocomplete="off" controlId={props.controlId}>
    <Form.Label>{props.Label}</Form.Label>
    <Form.Control type={props.type} placeholder={props.placeholder}
    value={credentials[props.type]} onChange={e=>{
      setCredentials({...credentials, [props.type]: e.target.value});
      ErrorChecker();
      }}
    />
    <Form.Text className="text-muted">
      {credentialMessage[props.type]}
      </Form.Text>
  </Form.Group>;
  }
  return(
    <Form className="FormAligner">
    {LoginDetails.map(LoginScreenRenderer)}
    <Button onClick={async(e)=>{
      e.preventDefault();
      const JSONString = credentials;
      const response = await fetch('http://localhost:5000/login',{
        method: 'POST',
        headers:{
          'Content-Type':'application/json'
        },
        body:JSON.stringify(JSONString)
      }).then(response=>response.json()).then((jsonData)=>{
        if(jsonData["Is_Valid"])
        {
          Auth.login("HelloWorld");
          props.history.push("/login-props-test");
        }
      });
    }}>Submit</Button>
    </Form>
  );
}

这是我的私有路由器的代码(对于 url:“/login-props-test”):

import React, { Component } from 'react';
import {Route,Redirect} from 'react-router-dom';
import Auth from '../security/Auth.jsx';


const ProtectedRoute = ({component: Component,...rest}) => {
  return(
    <Route {...rest} render ={
      (props)=>{
        alert(props);
        if(Auth.isAuthenticated())
        return <Component{...props} />
        else
        {
          return <Redirect to={
            {
              pathname: "/login",
              state: {
                from: props.location
              }
            }
          }/>
        }

      }
    }/>
  );
}

export default ProtectedRoute;

如果身份验证成功,我想将我的数据推送到另一个功能组件DisplayScreen.jsx,在那里我将呈现所有这些东西。这也是它的代码:

import React from 'react';

export default function DisplayScreen(props)
{
    //const isLoggedIn = props.isLoggedIn;
    const isLoggedIn = false;
    return(isLoggedIn?<div>
        <h1 class="ErrorPage-Header">Login Unsuccessful</h1>
        <p class="ErrorPage-Body">Seems like there were some issues while loggin you in.
        Maybe try to <a href='/login' className="href-AnchorTag">login again</a> or contact Administrator.</p>
        </div>:<div>
        <div className="row">
        <div className="block">Stats Info</div>
        <div className="block">Welcome to Your Dashboard</div>
        <div className="block">Logo</div>
        </div>
        <div>Toggle Button</div>
        <div className="row">
        <div className="block">Chart-01</div>
        <div className="block">Chart-02</div>
        <div className="block">Chart-03</div>
        </div>
        </div>);
}

我想将数据推送到这些道具。我创建的路线如下:

import React from 'react';
import StarterScreen from './components/screens/StarterScreen.jsx';
import LoginScreen from './components/screens/LoginScreen.jsx';
import RegisterScreen from './components/screens/RegisterScreen.jsx';
import DisplayScreen from './components/screens/DisplayScreen.jsx';
import 'bootstrap/dist/css/bootstrap.min.css';
import ProtectedRoute from './components/security/PrivateRoute.jsx';
import './App.css';
import {BrowserRouter,Route,Switch} from 'react-router-dom';
  function App(){
    return (
    <div className="App">
    <BrowserRouter>
    <Switch>
    <Route component={StarterScreen} exact path="/"></Route>
    <Route component={RegisterScreen} exact path="/register"></Route>
    <Route component={LoginScreen} exact path="/login"></Route>
    <ProtectedRoute component={DisplayScreen} exact path="/login-props-test" />
    </Switch>
    </BrowserRouter>
    </div>
  );
    }

export default App;

我的主要目标是将这些数据作为道具推送到DisplayScreen(props). 我知道这可能是一个非常简单的问题,但我是 React 的新手,所以任何形式的帮助都会非常感激。请注意,我将以获取凭据验证数据的方式在登录功能的提交按钮中获取 API 数据。我只是想知道在获取数据并将它们作为道具发送到DisplayScreen.

例如,代码将如下所示:

const response = await fetch('http://localhost:5000/login',{
        method: 'POST',
        headers:{
          'Content-Type':'application/json'
        },
        body:JSON.stringify(JSONString)
      }).then(response=>response.json()).then((jsonData)=>{
        if(jsonData["Is_Valid"])
        {
          const BackendData = await fetch('http://localhost:5000/fetch',{
            method: 'POST',
            headers:{
              'Content-Type':'application/json'
            },
            body:JSON.stringify(BackendData)
          }).then(response=>response.json()).then((jsonBackend)=>{
            //properties_to_pass = jsonBackend
            //Auth.login(properties_to_pass);
            props.history.push("/login-props-test");
          });
          
        }
      });

请帮助我实现同样的目标。提前致谢!

标签: javascriptreactjs

解决方案


用以下方法整理出来:

  1. 在登录函数中传递 JSONData:

    Auth.login(jsonBackend);

  2. 将该数据收集Auth.jsx为 props 属性:

    登录(道具){ this.authenticated = true; this.jsonData = 道具;}

  3. 返回 this 而不是 this.authenticated 并收集它 @ privateroute.jsx

const ProtectedRoute = ({component: Component,...rest}) => {
  return(
    <Route {...rest} render ={
      (props)=>{
        if(Auth.isAuthenticated().authenticated)
        return <Component{...Auth.isAuthenticated().jsonData} />
        else
        {
          return <Redirect to={
            {
              pathname: "/login",
              state: {
                from: props.location
              }
            }
          }/>
        }

      }
    }/>
  );
}

export default ProtectedRoute;

然后在我的displayscreen.jsx. 希望这可以帮助将来有人搜索它。


推荐阅读