首页 > 解决方案 > 如何将 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;

标签: reactjsreact-routerreact-domreact-typescript

解决方案


可以有多种方式将数据从一个组件传递到另一个组件:

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
  )
}

推荐阅读