React JS中点击搜索建议li触发history.push无法重定向问题咨询
问题原因及修复方案
form默认提交导致页面刷新:你的搜索栏包裹在form标签内,点击li时会触发form默认提交行为,页面重载后自然看不到finddoctor的执行日志,也不会执行跳转逻辑。
修复方法:给form标签添加阻止默认提交的逻辑:<form className="search-form" style={{}} onSubmit={e => e.preventDefault()}>子组件定义方式导致事件绑定失效:你把
SuggestionsList组件直接定义在父组件内部,父组件每次重渲染都会重建整个SuggestionsList,事件绑定会被重置导致点击不触发。
修复方法:- 把
SuggestionsList移到父组件外部定义 - 将
finddoctor作为props传递给SuggestionsList
父组件调用时新增props传值:
<SuggestionsList inputValue={inputValue} selectedSuggestion={selectedSuggestion} onSelectSuggestion={onSelectSuggestion} displaySuggestions={displaySuggestions} suggestions={filteredSuggestions} finddoctor={finddoctor} // 新增此行传递跳转函数 />在
SuggestionsList的props中接收该函数:const { suggestions, inputValue, onSelectSuggestion, displaySuggestions, selectedSuggestion, finddoctor // 新增此行接收跳转函数 } = props;- 把
路由跳转逻辑小错误:
- 你当前路径拼写多了空格:
history.push(/detiled/${e})最后有多余空格会导致跳转404,另外大概率是拼写错误,detiled应该是detail - 如果你使用的是react-router v6版本,
useHistory已经废弃,需要替换为useNavigate:
import { useNavigate } from 'react-router-dom'; // 组件内部声明 const navigate = useNavigate(); function finddoctor(id) { console.log(id); navigate(`/detail/${id}`); }- 你当前路径拼写多了空格:
内容的提问来源于stack exchange,提问作者vivek kn
相关产品推荐
相关产品推荐

