大家好,当我退出时,他们试图将用户\重定向到主页,但是却遇到了一些问题。我在react路由器中使用了重定向,并且应该重定向到主页,因为重定向是正确的,但是我收到一个奇怪的错误,说this2.setState不是函数。
有人知道这意味着什么吗?谢谢您的帮助!
import React from "react";
import {
Collapse,
Navbar,
NavbarToggler,
NavbarBrand,
Nav,
Button,
NavItem,
NavLink,
UncontrolledDropdown,
DropdownToggle,
DropdownMenu,
DropdownItem
} from "reactstrap";
import { withRouter } from "react-router";
import Icon from "react-icons-kit";
import { car } from "react-icons-kit/fa/car";
import { Redirect, Link } from "react-router-dom";
import app from "../config/dev";
export default class NavigatioBar extends React.Component {
constructor(props) {
super(props);
this.state = {
authenticated: false,
currentUser: null,
redirect: false,
isOpen: false
};
this.toggle = this.toggle.bind(this);
}
toggle() {
this.setState({
isOpen: !this.state.isOpen
});
}
signout() {
app
.auth()
.signOut()
.then(user => {
this.setState({ redirect: true });
});
}
componentWillMount() {
app.auth().onAuthStateChanged(user => {
if (user) {
this.setState({
currentUser: user,
authenticated: true
});
} else {
this.setState({
currentUser: null,
authenticated: false
});
}
});
}
render() {
const { redirect } = this.state;
if (redirect) {
return <Redirect to="/" />;
}
alert(this.state.authenticated);
const authenticated = this.state.authenticated;
return (
<div>
<Navbar color="primary" dark expand="md">
<div className="container">
<NavbarBrand href="/">
<Icon className="car-icon" icon={car} />
G66 CARS
</NavbarBrand>
<NavbarToggler onClick={this.toggle} />
<Collapse isOpen={this.state.isOpen} navbar>
<Nav className="ml-auto" navbar>
<NavItem>
<NavLink href="/cars">CARS</NavLink>
</NavItem>
<NavItem>
<NavLink href="/">FINANCE</NavLink>
</NavItem>
<NavItem>
<NavLink href="/">SERVICE</NavLink>
</NavItem>
<NavItem>
<NavLink href="/">PARTS</NavLink>
</NavItem>
<UncontrolledDropdown nav>
<DropdownToggle nav caret>
ABOUT
</DropdownToggle>
<DropdownMenu>
{authenticated ? (
<DropdownItem onClick={this.signout}>
<Button classname="btn-btn-primary">SignOut </Button>
</DropdownItem>
) : (
<DropdownItem>
<Link to="/login"> Login </Link>
</DropdownItem>
)}
<DropdownItem>ABOUT US</DropdownItem>
<DropdownItem>STAFF</DropdownItem>
<DropdownItem>CONTACT US</DropdownItem>
</DropdownMenu>
</UncontrolledDropdown>
</Nav>
</Collapse>
</div>
</Navbar>
</div>
);
}
}
答案 0 :(得分:1)
尝试在构造函数中绑定signout()
函数以获得this
上下文:
this.signout = this.signout.bind(this);
直到箭头函数,每个新函数都定义了自己的this
值。正如Anshul所写,箭头函数没有自己的this
上下文。因此,您可以在signout = () => {}
组件中使用NavigationBar
,它将自动访问其this
上下文。
答案 1 :(得分:1)
signout = () => {
app.auth().signOut().then((user) => {
this.setState ({ redirect: true })
})
}
退出没有此上下文。