简体   繁体   English

如何将 state 从登录组件发送到反应中的 RequireAuth 组件? 我正在使用 React 路由器

[英]How to send state from Login component to RequireAuth component in react? I am using React router

I am using react router version 6.3.0.我正在使用反应路由器版本 6.3.0。 I am trying to make protected route using RequireAuth.我正在尝试使用 RequireAuth 创建受保护的路由。 I am using Email, password login and posting the data using axios and tanstack/react-query.我正在使用 Email,密码登录并使用 axios 和 tanstack/react-query 发布数据。 What I am trying to do is send the isLoading and user state from Login comp.net to RequireAuth component.我想要做的是将isLoading用户state 从 Login comp.net 发送到 RequireAuth 组件。

This is my App.js component `这是我的 App.js 组件`

function App() {
  return (
    <div className="App">
      <Routes>
        <Route
          path="/"
          element={
            <RequireAuth>
              <Dashboard />
            </RequireAuth>
          }
        >
          <Route
            path="products"
            element={
              <RequireAuth>
                <Products />
              </RequireAuth>
            }
          />
          <Route
            path="products/create"
            element={
              <RequireAuth>
                <CreateProduct />
              </RequireAuth>
            }
          />
        </Route>
        <Route path="/login" element={<Login />} />
      </Routes>
      <ToastContainer />
    </div>
  );
}

` `

This is my Login component这是我的登录组件

` `

import { useMutation } from "@tanstack/react-query";
import axios from "axios";
import React, { useEffect, useState } from "react";
import { useForm } from "react-hook-form";
import { useLocation, useNavigate } from "react-router-dom";
import useToken from "../../hooks/useToken";
import Loading from "../shared/Loading";
import RequireAuth from "./RequireAuth";

const Login = () => {
  const [user, setUser] = useState(false);
  const [error, setError] = useState("");
  const navigate = useNavigate();
  let location = useLocation();
  let from = location.state?.from?.pathname || "/";
  const { access_token, refresh_token } = useToken(user);
  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm();
  let errorElement;


  const userLogin = async (data) => {
    const response = await axios.post(
      "http://www.example.com/auth/login",
      data
    );
    return response.data;
  };

  const { mutate, isLoading, isError } = useMutation(userLogin, {
    onSuccess: (data) => {
      setUser(data);
      console.log("USER:", data);
    },
    onError: (error) => {
      setError(error);
      console.log("ERROR:", error);
    },
  });

  if (isLoading) {
    return <Loading />;
  }

  if (isError) {
    errorElement = (
      <p className=" px-1 pb-2">
        <small className="text-red-500">Invalid user credentials</small>
      </p>
    );
  }

  const onSubmit = async (data) => {
    const user = { ...data };
    mutate(user);
  };

  return (
    // JSX
    // form is react hook form
  );
};

export default Login;

` `

RequireAuth component ` RequireAuth 组件`

import React from "react";
import { Navigate, useLocation } from "react-router-dom";
import Loading from "../Shared/Loading";

function RequireAuth({ children }) {
  let location = useLocation();

// I am trying to use the isLoading state sent from Login component here
   if (isLoading) {
     return <Loading></Loading>;
   }

// I am trying to use the user state sent from Login component here
   if (!user) {
     return <Navigate to="/login" state={{ from: location }} replace />;
   }

  return children;
}

export default RequireAuth;

` `

Can define the isLoading in App component level and pass it down to both components可以在App组件级别定义isLoading并将其传递给两个组件

const [isLoading, setIsLoading] = useState(false)
 <Route
      path="/"
      element={
        <RequireAuth isLoading={isLoading}>
          <Dashboard  />
        </RequireAuth>
      }
    >

    <Route path="/login" element={<Login setIsLoading={setIsLoading} />} />

Login登录

   const Login = ({setIsLoading}) => {

   useEffect(() => { setIsLoading(isLoading)}, [isLoading])

RequireAuth要求授权

function RequireAuth({ children,isLoading }) {
   if (isLoading) {
     return <Loading></Loading>;
   }

So the same for user as well所以用户也一样

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我正在从另一个组件更改 REACT 组件的 state 但没有刷新 - I am changing the state of the REACT component from another component but no refresh 反应路由器requireAuth不重定向 - React Router requireAuth not redirecting 如何将 state 从子组件发送到 React 中的另一个组件 - How to send state from Child component to another component in React 当我使用反应路由器 rom 时,组件没有重新渲染 - the component is not rerendering when i am using the react router rom 如何从路由器goback维护反应组件状态? - How to maintain react component state when goback from router? 我通过历史记录 (react-router-dom) 将 state 传递给 function 组件,但它表示 state 是“未定义” - I am passing the state to a function component via history (react-router-dom) but it says the state is 'undefined' 如何根据 React 中并行组件的操作(使用 React Router)更改组件的 state? - How to change state of component based on actions of parallel component in React (using React Router)? 我通过历史记录 (react-router-dom) 将 state 传递给 function 组件,但它表示 state 为“null” - I am passing the state to a function component via history (react-router-dom) but it says the state is 'null' 当登录状态处于组件状态时,如何使用 react-router 实现与登录相关的路径? - How to implement login-dependent paths with react-router, when the login-status is in the component-state? React Native:使用Tab Navigator将组件状态发送到其他组件 - React Native: Send component state to other component using Tab Navigator
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM