所以我使用 redirect
在 react-router-dom
我有两页纸。home
和 create
当形式 create
完成并已提交,它将执行 <Redirect>
函数,并且它工作了,但是 ComponentDidMount
没有再被解雇,我需要重新加载页面,以使。ComponentDidMount
为了让它重新开始,以下是我的代码。
我就是这样 redirect
在 Create
文件
if(this.state.createNew){
return <Redirect to='/home'/>
}
这是我的 ComponentDidMount
在我 Home
文件
componentDidMount() {
console.log("hi")
}
控制台打印 hi
只有在初始渲染时,当我重定向回页面时,它不会再次启动,我试图使用 setState
里面 ComponentDidMount
但它仍然没有被重新渲染。
当我尝试使用 Link to
方法,它的工作原理是 ComponentDidMount
又被开除了,但 Link to
不是我想要的,因为它不会像 <Redirect>
做
当我试着使用 "我的 "时,我得到了一个错误。useHistory
功能。
React Hook "useHistory" is called in function "simpan" which is neither a React function component or a custom React Hook function react-hooks/rules-of-hooks
这里是我如何使用我的 useHistory
:
function simpan(event){
event.preventDefault()
const email = event.target.elements.email.value
const name = event.target.elements.name.value
const admin = event.target.elements.admin.value
const active = event.target.elements.active.value
const history = useHistory()
console.log(email)
history.push('/home')
}
thanks before, anyhelp will be appriciated.
而不是 <Redirect />
你为什么不用 history.push('/home')
......这将带你到新的路线,一旦状态为真,并调用。componentDidMount
如何使用历史记录。
import { useHistory } from 'react-router-dom'
然后在你的组件中, const history = useHistory()
然后你是否需要改变路线。
history.push('/home')
如果你的 create
是类组件就用 this.props.history.push("/home")
而不是 <Redirect>
tag.As组件是您的路由,它将自动获得 create
组件是您的路由,它将自动获得 history
对象 props
.为什么在你的案例中使用历史记录而不是重定向标签?
使用react路由进行程序化导航的简单例子。 请在检查本例时检查浏览器的控制台