嗨,我使用 React-Typescript 创建了一个登录页面。用户使用用户名和密码登录,然后单击提交按钮 HttpPost 请求调用我的后端。如果我的响应状态成功。我的响应信息返回以返回我的 React 应用程序。我需要存储的响应数据并将数据传递到另一个页面。该页面调用 get 请求。在该 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;
答案 0 :(得分:0)
可以有多种方式将数据从一个组件传递到另一个组件:
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
)
}
答案 1 :(得分:0)
好的。那么,您想将 stream.filter(item => checkValid(item))
和 userId
从 userName
组件发送到 Login
组件吗?您可以通过 Home
从 Login
组件发送道具,并使用 Redirect
钩子在 Home
组件中访问这些道具。
useLocation