如何在基于类的组件中将用户重定向到页面



登录后我必须将用户重定向到'/dashboard'。但是我不想安装react-router-dom v5.2.0来使用history.push()。目前react-router-dom v6安装。是否有其他方法在登录后重定向用户。错误信息显示:er不能读取未定义的属性(读取'push')。

class Auth extends Component { 
constructor(props) {
super(props);
this.state = {
tab: 'signin'
}
}
SignIn = (email, password) => {
axios.post('/api/users/login', {email, password}).then(res => {
//console.log(res);
if(res.data.success) {
store.dispatch({
type: 'login',
_id: res.data.user._id,
user: res.data.user,
token: res.data.token
});
console.log(store.getState());
// Problem arises here.
this.props.history.push('/dashboard');               
}
}).catch(er => {
if (er.response) {
console.log(er.response.data);
console.log(er.response.status);
console.log(er.response.headers);
} else if (er.request) {
console.log(er.request);
} else {
console.log('er', er.message);
}
console.log(er.config);
})     
}

useNavigate是一个react钩子,因此只能在功能组件中使用。如果你的父组件是一个功能组件,你能做的就是把navigate作为一个prop传递。像这样:

const ParentComponent = () => {
const navigate = useNavigate(); 
return <Auth navigation={navigate} /> //pass to your component.
}

你可以尝试在你的组件中使用它。

相关内容

最新更新