在react路由器中使用历史记录方法时出错



添加联系人后,我尝试使用历史记录方法导航到主页,但我在控制台中不断收到此错误,表单无法导航

Search for the keywords to learn more about each error.
ERROR in [eslint]
srcApp.js
Line 43:17:  Unexpected use of 'history'  no-restricted-globals

这是我的代码


render(){
return(
<div className="appName">
<Routes>
<Route  path="/" element={
<ListContacts
contacts={this.state.contacts}
deleteContact={this.removeContact}
/>
}/>
<Route path="/create" element={
<CreateContact 
onCreateContact = {(contact)=>{
this.createContact(contact)
history.push("/")
}}
/>
}/>
</Routes>
</div>
)
}
}

export default App;

要访问history实例,您必须掌握它。

错误

您会得到这个错误,因为如果没有useHistoryhistory引用实际上指向全局Window.history对象。由于这个原因,你得到了"意外使用"history"无限制全局变量">

修复

如果使用类组件,则可以通过this.props.history获取history实例。为此,请确保您使用的是withRouterHOC。之后你可以使用:

this.props.history.push("/")

如果您使用的是功能组件,您可以利用useHistory():

import { useHistory } from "react-router-dom";  // <-- added this import
const history = useHistory();            //  <----- added this line
return(
...
onCreateContact = {(contact)=>{
this.createContact(contact)
history.push("/")
}}
...

最新更新