我一直在尝试使用react-router-dom在ReactJS中创建一个重定向错误页面。此页将显示一个
错误
消息,然后使用来自react-router-dom的{ Redirect }重定向到主页。此重定向将在1.5秒后发生
我曾尝试使用setTimeOut函数来实现1.5秒的延迟,但结果与我预期的不同。我希望页面重定向到'/‘主页,但在浏览器中只显示数字"2“。
import React, {Component} from 'react';
import {Redirect} from 'react-router-dom';
class Error extends Component {
myFunc = () => (<Redirect to={'/'} />)
render(){
return(
<div>
<h1>ERROR!!!!</h1>
{setTimeout(()=>(this.myFunc), 1500)}
</div>
)
}
}
export default Error我希望页面重定向到homePage,但错误下面没有重定向!消息我只看到了一个数字2。有人能解释一下我做错了什么吗?
发布于 2019-07-21 07:56:19
在呈现组件时,您看到的2是来自setTimeout的返回值,这是创建的计时器的id。计时器本身稍后结束,它返回的react元素将被忽略。如果你想在超时后重定向,你必须向组件添加状态,例如:
class Error extends Component {
state = { shouldRedirect: false }
componentDidMount() {
setTimeout(() => this.setState({ shouldRedirect: true }), 1500)
}
render() {
if (this.state.shouldRedirect) {
return <Redirect to={'/'} />
}
return (
<div>
<h1>ERROR!!!!</h1>
</div>
)
}
}发布于 2019-07-21 07:39:56
setTimeout的结构是:
setTimeout(
function(){
// Your code
}, 1500);尝试将您的超时时间更改为setTimeout(()=>{this.myFunc()}, 1500)
https://stackoverflow.com/questions/57129222
复制相似问题