React Router Link点击不跳转 手动输入对应URL可正常访问问题咨询
问题根因
你遇到的Link不生效问题核心原因是组件嵌套定义导致Router上下文丢失:
你把SuggestionsList组件直接写在了Searchclients组件内部,每当Searchclients的状态(比如输入框的值inputValue、搜索建议列表filteredSuggestions等)发生更新时,SuggestionsList都会被重新创建为全新的组件实例,内部的Link组件无法继承到外层Router的路由上下文,因此跳转逻辑失效。
而你放在SuggestionsList外部的Link可以正常跳转,也验证了这个问题的存在。
另外还有一个潜在影响点:你的搜索结果包裹在form标签内部,点击元素可能触发表单默认提交行为,导致页面刷新,干扰路由跳转。
修复方案
步骤1:将SuggestionsList组件移到Searchclients外部定义
不要在组件内部嵌套定义其他组件,避免每次重渲染被重建:
// 把SuggestionsList移到Searchclients外面 const SuggestionsList = (props) => { const { suggestions, inputValue, onSelectSuggestion, displaySuggestions, selectedSuggestion, } = props; if (inputValue && displaySuggestions) { if (suggestions.length > 0) { return ( <ul className="suggestions-list" style={styles.ulstyle}> {suggestions.map((suggestion, index) => { const isSelected = selectedSuggestion === index; const classname = `suggestion ${isSelected ? "selected" : ""}`; return ( <Link to={`/detiled/${suggestion.id}`} key={index}> <li style={styles.listyle} className={classname} > {suggestion.firstname} </li> </Link> ); })} </ul> ); } else { return <div>无可用搜索建议...</div>; } } return <></>; }; const Searchclients = () => { // 原有Searchclients的其他逻辑保持不变 }
步骤2:阻止form标签默认提交行为
给搜索的form标签添加onSubmit事件,阻止默认提交刷新页面:
<form className="search-form" style={{}} onSubmit={(e) => e.preventDefault()}> {/* 原有form内部内容保持不变 */} </form>
完成以上两步修改后,搜索结果的Link即可正常跳转。
内容的提问来源于stack exchange,提问作者vivek kn
相关产品推荐
相关产品推荐

