已超过最大更新深度。当组件重复调用componentWillUpdate
或componentDidUpdate
内部的setState时,可能会发生这种情况。 React限制了嵌套更新的数量,以防止无限循环。
import React, { Component } from "react";
import { BrowserRouter, Route, Redirect, Switch } from "react-router-dom";
import Login from "./component/auth/Login";
import HomeScreen from "./component/home-screen/HomeScreen";
class App extends Component {
constructor(props) {
super(props);
this.state = {
user: {}
};
}
componentDidMount() {
this.authListener();
}
authListener() {
firebase.auth().onAuthStateChanged(user => {
if (user) {
this.setState({ user });
} else {
this.setState({ user: null });
}
});
}
render() {
return (
<BrowserRouter>
<div className="App">
<Switch>
<Route exact path="/" component={Landing} />
{this.state.user ? (
<Redirect to="/homescreen" />
) : (
<Redirect to="/login" />
)}
<Route exact path="/login" component={Login} />
<Route exact path="/homescreen" component={HomeScreen} />
<Route exact path="/users" component={Users} />
<Route exact path="/users/:id" component={UserDetail} />
<Route component={Error} />
</Switch>
</div>
</BrowserRouter>
);
}
}
export default App;
答案 0 :(得分:1)
反应路由器v4 +支持使用PrivateRoute
。
// create a private route, if user is not logged in redirect to login page
const PrivateRoute = ({ component: Component, ...rest }) => (
<Route {...rest} render={(props) => (
isAuthenticated() === true
? <Component {...props} />
: <Redirect to='/login' />
)} />
)
像普通路由一样使用它,并在专用路由中检查身份验证。
<BrowserRouter>
<Route path="/login" exact component={FormularAuth} />
<PrivateRoute path='/private' component={Private} />
</BrowserRouter>
答案 1 :(得分:0)
//App.js
class App extends Component {
constructor(props) {
super(props);
this.state = {
user: ""
};
}
componentDidMount() {
this.authListener();
}
authListener() {
firebase.auth().onAuthStateChanged(user => {
if (user) {
this.setState({
user
});
} else {
this.setState({
user: null
});
}
});
}
render() {
return (
<BrowserRouter>
<div className="App">
<Switch>
<Route exact path="/" component={(props)=><Landing {...props} users = {this.state.user}/>}/>
<Route exact path="/login" component={Login} />
<Route exact path="/homescreen" component={HomeScreen} />
</Switch>
</div>
</BrowserRouter>
);
}
}
export default App;
在着陆组件中检查用户值,然后导航到相应的路线。
//Landing.js
class Landing extends Component {
componentDidMount() {
if (this.props.users) {
this.props.history.push("homescreen")
} else if (this.props.users === null) {
this.props.history.push("login")
}
}
render() {
return (
<div>
<h1>landing page</h1>
</div>
);
}
}