重定向并将从API获取的数据同时传递到React JS的另一个组件中。

huangapple go评论66阅读模式
英文:

Redirection & Pass data fetched from API to another component in React JS simultaneously

问题

I wanted to redirect from login page to dashboard upon getting a successful response from API & pass the success message fetched through API from one component to another component at the same time. By doing so, I ultimately aim to redirect user from login page to dashboard with displaying toast message received on the success response of login API.

Login Component

import { useNavigate } from "react-router-dom";
import { ToastContainer, toast } from 'react-toastify';

export default function Login() {
  const nav = useNavigate();

  const authenticateUser = () => {
    const endpoint = `${baseUrl}/login`;
    fetch(endpoint, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(loginState)
    })
    .then(response => response.json())
    .then(data => {
      if (data.statusCode === 200) {
        let toastMsg = data.message;
        nav("/dashboard", { toastMsg: toastMsg });
      }
    })
    .catch(error => console.log(error))
  }
}

Dashboard Component

import { ToastContainer, toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import { useEffect } from "react";
import { useLocation } from 'react-router-dom';

const Dashboard = () => {
  const location = useLocation();

  useEffect(() => {
    if (location.state.toastMsg) {
      toast(location.state.toastMsg);
    }
  }, [location.state.toastMsg]);

  return (
    <div>
      <p>Welcome to your Dashboard</p>
      <ToastContainer />
    </div>
  );
};
export default Dashboard;

以上是您提供的代码的翻译部分。

英文:

I wanted to redirect from login page to dashboard upon getting a successful response from API & pass the success message fetched through API from one component to another component at the same time. By doing so, I ultimately aim to redirect user from login page to dashboard with displaying toast message received on the success response of login API.

I used the useNavigate,useLocation hooks to implement this. My code does the redirection but not able to catch the data, in "Dashboard" component, which is passed from the "Login" component. I am completely a newbie to React JS. Any help is much appreciated.

Login Component

import { useNavigate } from &quot;react-router-dom&quot;;
import { ToastContainer, toast } from &#39;react-toastify&#39;;

export default function Login() {
const nav = useNavigate();

 const authenticateUser = () =&gt; {

        const endpoint = `${baseUrl}/login`;
        fetch(endpoint,
            {
                method: &#39;POST&#39;,
                headers: {
                    &#39;Content-Type&#39;: &#39;application/json&#39;
                },
                body: JSON.stringify(loginState)
            }).then(response =&gt; response.json())
            .then(data =&gt; {
                
                if (data.statusCode === 200) {
                    let toastMsg = data.message;
                    nav(&quot;/dashboard&quot;,{toastMsg: toastMsg});
                }
             }).catch(error =&gt; console.log(error))
    }
}

Dashboard Component

import { ToastContainer, toast } from &#39;react-toastify&#39;;
import &#39;react-toastify/dist/ReactToastify.css&#39;;
import { useEffect } from &quot;react&quot;;
import {useLocation} from &#39;react-router-dom&#39;;


const Dashboard = () =&gt; {
    const location = useLocation();
  
    useEffect(() =&gt; {
        console.log(location) 
        if (location.state.toastMsg) {

            toast(location.state.toastMsg)
        }, [location.state.toastMsg]
    }
    )
  });
    return (
      &lt;div&gt;
        &lt;p&gt;Welcome to your Dashboard&lt;/p&gt;
        &lt;ToastContainer /&gt;
      &lt;/div&gt;
    );
  };
  export default Dashboard;

Below shown is the screenshot of the console tab.

重定向并将从API获取的数据同时传递到React JS的另一个组件中。

答案1

得分: 0

你在使用navigate时需要在state键中传递数据:
在你的示例中使用以下方式:

nav('/dashboard', {
  state: {
    toastMsg: toastMsg,
  },
});

然后使用const location = useLocation()来获取它。传递的对象将在location.state中。

在这里查看示例:https://codesandbox.io/s/restless-frost-ji3ww6

英文:

You have to pass data in state key when using navigate:
In your example use this:

nav(&#39;/dashboard&#39;, {
  state: {
    toastMsg: toastMsg,
  },
});

Then get it using const location = useLocation() . passed object will be in location.state

See example here: https://codesandbox.io/s/restless-frost-ji3ww6

huangapple
  • 本文由 发表于 2023年6月8日 19:31:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/76431408.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定