reactjs - 如何将 API 响应数据传递到另一个反应页面
问题描述
您好我已经使用 React-Typescript 创建了一个登录页面。用户使用用户名和密码登录,然后单击提交按钮 HttpPost 请求调用我的后端。如果我的响应状态成功。我的响应信息返回以返回我的 React 应用程序。我需要存储的响应数据并将数据传递到另一个页面。该页面调用获取请求。在那个 getrequest 参数中,我将发送响应数据。
例如:用户成功登录。后端发送到响应(userId,userName)。然后重定向主页。我的主页有Httpget请求(fetch("http:localhost:8080/api/getuser")。我需要在http请求中传递userId和userName(fetch("http:localhost:8080/api/getuser?userId= "+userId"&userName="+userName)
登录 tsx 文件:
import React from 'react';
import { Redirect } from 'react-router-dom';
import { SyntheticEvent, useState } from 'react';
import { Link } from 'react-router-dom';
const { REACT_APP_API_ENDPOINT } = process.env;
const Login = (props: { setName: (name: string) => void }) => {
const [userName, setuserName] = useState('');
const [userid, setuserId] = useState('');
const [password, setPassword] = useState('');
const [redirect, setRedirect] = useState(false);
const submit = async (e: SyntheticEvent) => {
e.preventDefault();
const response = await fetch(`${REACT_APP_API_ENDPOINT}/login`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify({
userName,
password
})
});
const content = await response.json();
console.log(content);
setRedirect(true);
props.setName(content.userName);
setuserId(content.userId);
console.log(content.userId);
}
if (redirect) {
return <Redirect to="/" />
}
return (
<div>
<form onSubmit={submit} className="form-signin">
<h1 className="h3 mb-3 fw-normal">Please sign in</h1>
<div>
<input type="userName" className="form-control" placeholder="UserName" required
onChange={e => setuserName(e.target.value)} />
</div>
<div>
<input type="password" className="form-control" placeholder="Password" required
onChange={e => setPassword(e.target.value)} />
</div>
<button className="w-100 btn btn-lg btn-primary" type="submit">Log in</button>
</form>
</div>
);
};
export default Login;
应用 tsx 文件
import React, { Component } from 'react';
function Home() {
const { REACT_APP_API_ENDPOINT } = process.env;
const [name, setName] = useState('');
const [id, setId] = useState('');
useEffect(() => {
(
async () => {
const response = await fetch(`${REACT_APP_API_ENDPOINT}/getuser`, {
headers: { 'Content-Type': 'application/json' }
})
.then(function (response) {
console.log(response);
})
const content = await response;
//setName(content.name);
}
)();
});
return ();
export default Home;
解决方案
可以有多种方式将数据从一个组件传递到另一个组件:
Using Props. You can use props to pass data from parent to child component. ...
|--- App.js
|---- ParentComponent
|----ChildComponent
Using React ContextAPI or State management library like Redux. ...
Using Props as Callback Function.
<Link
to={{
pathname: "/page",
data: data // your data array of objects
}}
>
//in /page
render() {
const { data } = this.props.location
return (
// render logic here
)
}
推荐阅读
- javascript - 增加复制的字符串编号javascript
- r - foreach %dopar% 中的表达式()
- python - 如何使用 brew 并为 Python 3.6.8 安装 precommit
- image-processing - 更压缩的 ppm 或 bmp 版本?
- docker - 失败错误:调用注册端点失败并出现错误 [错误:连接 ECONNREFUSED 127.0.0.1:7054] | ca_peerOrg1 和 ca_peerOrg2 未运行
- r - 获取由 R 中的多个变量分组的数据框的比例
- javascript - Swiper Js - 仅当设备宽度小于或等于 515 时才启动滑块
- react-native - 在应用程序中使用 redux 状态时,切换检查器不起作用
- python-3.x - 即使我得到很好的输出也会出错
- python - 如何在python中使用GEV估计最大似然