React中控制台日志/错误重复打印3-4次的原因咨询
React控制台重复打印日志/错误的问题修复
问题原因分析
- 日志位置错误:你把
console.log(arr)写在了filter的回调函数内部,每匹配到一个符合条件的result就会执行一次打印,匹配几个结果就会打印几次。 - React严格模式(StrictMode):开发环境下StrictMode会重复调用组件函数、事件处理相关逻辑来检测副作用,这会导致日志/错误被额外打印1次(通常是两次),如果叠加其他渲染触发,次数会到3-4次。
- 路由导航后的组件重复渲染:
navigate('/SearchResult')后,若SearchBar组件在目标页面也存在,可能触发组件重新挂载/渲染,导致逻辑重复执行。
具体修复步骤
1. 修正日志打印位置并优化过滤逻辑
把打印操作移到filter外部,确保只打印最终结果;同时优化filter的使用方式(无需手动push数组,直接利用filter的返回值),还要替换match为更安全的includes避免正则特殊字符问题:
const SearchBar = ({ carddata}) => { const navigate = useNavigate(); function searchResult(e) { if (e.key === "Enter") { const inputValue = e.target.value.trim(); if (!inputValue) return; // 直接用filter生成匹配数组,无需手动维护arr const matchedResults = carddata.filter(result => `${result.heading}`.toLowerCase().includes(inputValue.toLowerCase()) ); // 只打印最终结果一次 console.log(matchedResults); if(window.location.pathname !== '/SearchResult') { navigate('/SearchResult'); } } } return ( <div className="flex"> <input onKeyDown={searchResult} className="search-input w-100 br bb fw4" type="text" placeholder="Search here..." /> <SearchIcon className="search-icon h2 br bb hover-black" style={{ fill: "red" }} sx={{ fontSize: 40 }} /> </div> ) }
2. 处理StrictMode的重复触发(可选)
开发环境下StrictMode的重复执行是正常的检测机制,生产环境会自动消失。如果不想在开发时看到重复日志,可以用useRef标记是否已经打印:
const SearchBar = ({ carddata}) => { const navigate = useNavigate(); const hasPrinted = useRef(false); // 标记是否已打印 function searchResult(e) { if (e.key === "Enter") { const inputValue = e.target.value.trim(); if (!inputValue) return; hasPrinted.current = false; // 重置标记 const matchedResults = carddata.filter(result => `${result.heading}`.toLowerCase().includes(inputValue.toLowerCase()) ); if (!hasPrinted.current) { console.log(matchedResults); hasPrinted.current = true; } if(window.location.pathname !== '/SearchResult') { navigate('/SearchResult'); } } } // 返回部分不变 }
3. 检查路由结构
确认SearchResult页面是否也渲染了SearchBar组件,如果是,导航后组件会重新挂载,可能导致逻辑重复触发。可以调整路由,或者用状态管理(比如Context、Redux)传递搜索结果,避免重复执行过滤逻辑。
内容的提问来源于stack exchange,提问作者SHERAWAT LOKESH
相关产品推荐
相关产品推荐

