React JS中API请求成功后跳转并同步传递数据的问题
React Router跳转传递数据失败解决方案
问题原因
- 登录组件传递数据方式错误:使用
useNavigate跳转时,自定义数据必须放在state属性中,你当前直接传递对象,导致数据未被正确挂载到location.state上。 - 仪表盘组件语法错误:
useEffect写法存在语法问题,且未先判断location.state是否存在就直接访问子属性,可能引发报错。
修正后的代码
登录组件
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) { const toastMsg = data.message; // 正确写法:将数据放在state属性中传递 nav("/dashboard", { state: { toastMsg } }); } }) .catch(error => console.log(error)) } // 补充组件基础渲染结构 return ( <div> {/* 登录表单等内容 */} <button onClick={authenticateUser}>登录</button> <ToastContainer /> </div> ); }
仪表盘组件
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(() => { console.log(location); // 先判断state是否存在,再访问toastMsg避免报错 if (location.state?.toastMsg) { toast(location.state.toastMsg); } }, [location.state]); return ( <div> <p>Welcome to your Dashboard</p> <ToastContainer /> </div> ); }; export default Dashboard;
关键说明
useNavigate跳转时,第二个参数是配置对象,自定义数据必须放在state字段中,才能通过useLocation的state属性获取。- 使用可选链操作符
?.,可以避免location.state为undefined时访问toastMsg引发的报错。 - 确保组件返回正确的JSX结构,原登录组件缺少返回部分,会导致组件无法正常渲染。
内容的提问来源于stack exchange,提问作者M G
相关产品推荐
相关产品推荐

