React路由跳转后如何在目标页面显示上一步操作成功的通知
问题原因
你当前代码的问题是:AddEmployee 组件调用history.push跳转后,当前组件的notify状态会随组件卸载失效,无法传递到SingleEmployee页面,需要通过路由传参把通知参数带到目标页面。
实现步骤
第一步:修改AddEmployee.js的提交逻辑
把提交成功后的通知参数放到路由跳转的state中,不需要在当前组件设置notify:
// handleUpdate 成功分支修改为以下逻辑 if (result.httpStatus === 200) { history.push("/user/" + employeeId, { notify: { isOpen: true, message: '新增成功', type: 'success' } }); // 原有setNotify代码直接删除即可,当前组件即将跳转,设置状态无意义 }
第二步:修改SingleEmployee.js接收路由参数触发通知
引入useLocation读取跳转携带的参数,触发通知后清空路由state,避免刷新或二次进入页面重复弹出通知:
import { useParams, useLocation, useHistory } from 'react-router-dom'; const SingleEmployee = () => { const { id } = useParams(); const location = useLocation(); const history = useHistory(); const [notify, setNotify] = useState({ isOpen: false, message: '', type: '' }) const [firstName, setFirstName] = useState(); const [lastName, setLastName] = useState(); async function getSingleUser() { // 原有获取用户信息的逻辑保持不变 if (result.httpStatus === 200) { setFirstName(result.result[0].firstName); setLastName(result.result[0].lastName); } } useEffect(() => { getSingleUser(); // 判断是否是从新增员工页面跳转过来的 if (location.state?.notify) { setNotify(location.state.notify); // 清空路由state,避免刷新页面重复弹通知 history.replace({ pathname: location.pathname, state: {} }) } }, []); // 原有渲染逻辑保持不变 return ( <> <label>{firstName}</label><br /> <label>{lastName}</label> <Notification notify={notify} setNotify={setNotify} /> </> ); } export default SingleEmployee;
修改完成后,只有从新增员工页面提交成功跳转过来时才会弹出通知,其他场景进入员工详情页不会触发通知,完全符合需求。
内容的提问来源于stack exchange,提问作者nour
相关产品推荐
相关产品推荐

