REACTJS 和 API 将 Api 的值传递给另一个页面
Posted
技术标签:
【中文标题】REACTJS 和 API 将 Api 的值传递给另一个页面【英文标题】:REACTJS AND API pass the value of Api to another page 【发布时间】:2020-05-09 08:36:12 【问题描述】:我真的需要帮助,因为我对 reactjs 完全陌生。如何维护整个页面的登录用户?就像一个会话。代码显示了我登录时调用的数据。我真的迷失了这里的反应。
当凭据为真时,结果如下
userId: 1, firstname: "Jeff", middlename: null, lastname: "Geli", positionId: 1, …
userId: 1
firstname: "Jeff"
middlename: null
lastname: "Geli"
positionId: 1
token: "eyJhbGciOiJodHRwOi8vd3d3LnczLm9yZy8yMDAxLzA0L3htbGRzaWctbW9yZSNobWFjLXNoYTI1NiIsInR5cCI6IkpXVCJ9.eyJMb2dnZWRVc2VyIjoie1wiVXNlcklkXCI6MSxcIkZpcnN0bmFtZVwiOlwiSmVmZlwiLFwiTWlkZGxlbmFtZVwiOm51bGwsXCJMYXN0bmFtZVwiOlwiR2VsaVwiLFwiUG9zaXRpb25JZFwiOjEsXCJUb2tlblwiOm51bGx9IiwiZXhwIjoxNTc5NzU5MzI5LCJpc3MiOiJzbWVzay5pbiIsImF1ZCI6InJlYWRlcnMifQ.xXPW0ijBdULuMBfhFGyL1qF1bA--FzG64jEJVMQZWY8"
__proto__: Object
import React from 'react';
import Link, withRouter from 'react-router-dom';
import PageSettings from './../../config/page-settings.js';
import bg from '../../assets/login-bg-17.jpg';
import axios from "axios";
class LoginV2 extends React.Component
static contextType = PageSettings;
constructor(props)
super(props);
//credentials for login
this.state =
username: '',
password: '',
;
this.handleSuccess = this.handleSuccess.bind(this);
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
componentDidMount()
this.context.handleSetPageSidebar(false);
this.context.handleSetPageHeader(false);
componentWillUnmount()
this.context.handleSetPageSidebar(true);
this.context.handleSetPageHeader(true);
handleChange(event)
this.setState(
[event.target.name]: event.target.value
);
;
handleSuccess(data)
alert("Logged IN");
this.props.history.push('dashboard/v2');
//When submit button is clicked, fetch API
async handleSubmit(event)
event.preventDefault();
//fetch API, method POST
const getCred = await fetch('/api/login',
headers:
'Accept': 'application/json',
'Content-Type': 'application/json',
'ApiKey': "Secret"
,
method: "POST",
body: JSON.stringify(
username: this.state.username,
password: this.state.password
),
);
const data = await getCred.json();
if (getCred.status == 400)
alert(data);
else
this.handleSuccess(getCred);
console.log(data);
render()
return (
<React.Fragment>
<div className="login-cover">
<div className="login-cover-image" style=backgroundImage:'url('+ bg +')' >
</div>
<div className="login-cover-bg"></div>
</div>
<div className="login login-v2">
<div className="login-header">
<div className="brand">
<span className="logo"></span> <b>Tek</b> Teach
<small>Leraning Management System</small>
</div>
<div className="icon">
<i className="fa fa-lock"></i>
</div>
</div>
<div className="login-content">
<form className="margin-bottom-0" onSubmit=this.handleSubmit>
<div className="form-group m-b-20">
<input type="text" className="form-control form-control-lg" placeholder="Username" name="username" value=this.state.username onChange=this.handleChange required />
</div>
<div className="form-group m-b-20">
<input type="password" className="form-control form-control-lg" placeholder="Password" name="password" value=this.state.password onChange=this.handleChange required />
</div>
<div className="login-buttons">
<button type="submit" className="btn btn-success btn-block btn-lg" onClick=this.login>Sign me in</button>
</div>
</form>
</div>
</div>
</React.Fragment>
)
export default withRouter(LoginV2);
【问题讨论】:
【参考方案1】:您可以使用sessionStorage
或localStorage
来存储令牌,然后检查它,如果已设置,则保持用户登录,否则注销用户。
在用户登录后设置会话
if (token)
localStorage.setItem('session', JSON.stringify(token));
检查用户是否登录
let user = localStorage.getItem('session');
if (user)
console.log('Valid session');
else
console.log('Not valid session');
注销时清除值
let user = localStorage.getItem('session');
if (user)
localStorage.removeItem();
在提供的代码中添加逻辑
async handleSubmit(event)
// .... Other code
const data = await getCred.json();
if (data.status == 400)
alert(data);
else
this.handleSuccess(data);
console.log(data);
//Set your token in handleSuccess method
handleSuccess(data)
alert("Logged IN");
if (data.token)
localStorage.setItem('session', JSON.stringify(data.token));
this.props.history.push('dashboard/v2');
【讨论】:
嗨,Sohail 感谢您提供的出色代码,它是否会像我成功登录时那样存储到另一个页面,会话是否仍然存在?即使刷新?我该怎么做,我应用了代码,但无法在仪表板上获取会话。 localStorage 可跨应用程序使用,您可以从应用程序中的任何页面访问它。它也会在页面刷新时持续存在。 您可以通过localStorage.getItem('session')
获取它
打开开发者工具,进入应用程序选项卡,然后点击本地存储,您应该会看到会话条目。
我现在明白了,非常感谢!!在 React 中苦苦挣扎以上是关于REACTJS 和 API 将 Api 的值传递给另一个页面的主要内容,如果未能解决你的问题,请参考以下文章
无法将 access_token 传递给 Reactjs 中的端点
如何从 Reactjs 中的 useEffect 挂钩访问道具
React JS - 如何将变量(参数)传递给 API URL?