我正在尝试将用户重定向到,/dashboard
如果用户已登录,但是我遇到此错误:
TypeError:无法读取未定义的属性“ push”
我的家庭组件:
const Home = (props) => {
const { isLoggedIn } = useSelector((state) => state.login);
if (isLoggedIn) {
props.history.push("/dashboard"); // This line is producing the error
window.location.reload();
}
return (
<div>
<Header />
<Switch>
<Route exact path='/login' component={Login} />
<Route exact path='/dashboard' component={Dashboard} />
<Redirect to='/' />
</Switch>
</div>
);
};
export default Home;
我对props.history.push("/dashboard");
我的登录组件尝试了相同的方法(),但没有得到任何错误。我想知道为什么会发生此错误,以及如何解决此问题?
import React, {useEffect} from 'react'
import {useHistory} from 'react-router-dom'
const Home = () => {
const history = useHistory()
const { isLoggedIn } = useSelector((state) => state.login);
useEffect(()=> {
if (isLoggedIn) {
history.push("/dashboard"); // This line is producing the error
}
},[isLoggedIn, history]) //also add history dependency
return (
<div>
<Header />
<Switch>
<Route exact path='/login' component={Login} />
<Route exact path='/dashboard' component={Dashboard} />
<Redirect to='/' />
</Switch>
</div>
);
};
export default Home;
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句