React中使用react-router-dom的Prompt组件确认跳转后如何清空输入框内容
问题原因
该现象由两个特性共同导致:
- 处于Home页面时点击Home导航链接,目标路由与当前路由完全一致,React Router不会触发Home组件重新挂载,输入框绑定的state自然不会自动重置
- 官方提供的
<Prompt>组件仅封装了基础的拦截弹窗能力,没有对外暴露用户确认跳转后的回调钩子,无法直接插入清空逻辑
解决方案
直接使用React Router底层的history.blockAPI替代<Prompt>组件,完全自定义拦截逻辑即可实现需求,修改后的完整代码如下:
import { useState, useEffect } from 'react'; import { useHistory } from 'react-router-dom'; const Home = () => { const [value, setValue] = useState(""); const history = useHistory(); // 只有输入框有内容时才触发跳转拦截,符合需求场景 const shouldBlock = !!value; useEffect(() => { // 注册路由拦截器 const unblock = history.block((targetLocation) => { if (shouldBlock) { if (window.confirm("Are you sure?")) { // 用户确认跳转后,如果目标是Home路由则清空输入框 if (targetLocation.pathname === '/') { setValue(''); } return true; } return false; } return true; }); // 组件卸载时移除拦截器 return () => unblock(); }, [history, shouldBlock]); const onChange = (e) => { setValue(e.target.value); }; return ( <div> <input value={value} onChange={onChange} /> <h2>Home</h2> </div> ); }; export default Home;
注:代码中的
targetLocation.pathname === '/'需要替换为你实际的Home路由路径。
内容的提问来源于stack exchange,提问作者Asking
相关产品推荐
相关产品推荐

