当用户单击注销按钮时,它会从本地存储中清除 token ,也会将状态更改为注销,但它不会重定向到我想要的,因为它单击按钮会重定向到登录页面。
import React, { Component } from "react";
import "./Logout.module.css";
import * as action from '../../store/actions';
import { connect} from 'react-redux';
import { Redirect } from 'react-router';
class Logout extends Component {
constructor(props) {
super(props);
this.state = {
loggedOut:false,
redirect:null
};
}
handleSubmit = event => {
event.preventDefault();
this.props.onAuth( this.state);
};
componentWillReceiveProps(nextProps) {
if(nextProps!== this.props){
if(nextProps.loggedOut){
this.setState({
redirect: <Redirect to='/login' />
})
}
}
}
render() {
return (
<form onSubmit={this.handleSubmit}>
{this.state.redirect}
<button type="submit">LOGOUT</button>
</form>
);
}
}
const mapStateToProps = state => {
return {
loggedOut: state.loggedOut
}
}
const mapDispatchToProps = dispatch =>{
return{
onAuth:() =>dispatch(action.logout())
};
};
export default connect(mapStateToProps,mapDispatchToProps) (Logout);
最佳答案
您只需更改 if
声明。
componentWillReceiveProps(nextProps) {
if(nextProps.loggedOut && nextProps.loggedOut!== this.props.loggedOut){
this.setState({
redirect: <Redirect to='/login' />
})
}
}
此外,仅供引用,您应该停止使用 componentWillReceiveProps
钩子(Hook)改为使用 componentDidUpdate
并检查 prevProps
。了解已弃用的生命周期 Hook Here
componentDidUpdate(prevProps) {
if(prevProps.loggedOut && prevProps.loggedOut!== this.props.loggedOut){
this.setState({
redirect: <Redirect to='/login' />
})
}
}
使用 withRouter
会好得多和history.push
而不是<Redirect to={"/"} />
关于javascript - 我的重定向在单击注销时不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58691878/