我正在尝试在 App.js 中为经过身份验证的用户添加受保护的路由,但 react 元素被多次渲染。下面是我的 App.js 代码
class App extends Component {
constructor(props) {
super(props);
this.state = {
currentUser: null,
isAuthenticated: false,
isLoading: false
}
}
async loadCurrentUser() {
this.setState({
isLoading: true
});
await getCurrentUser()
.then(response => {
this.setState({
currentUser: response,
isAuthenticated: true,
isLoading: false
});
}).catch(error => {
this.setState({
isLoading: false
});
});
}
async componentDidMount() { await this.loadCurrentUser(); } render() {
return (
<BrowserRouter>
<React.Suspense fallback={loading}>
<Switch>
<Route exact path="/login" component={Login} />
<Route exact path="/register" component={Register} />
<ProtectedRoute path="/" name="Home" authenticated={this.state.isAuthenticated}
component={TheLayout} handleLogout={this.handleLogout}></ProtectedRoute>
</Switch>
</React.Suspense>
</BrowserRouter>
);
}
}
答案 0 :(得分:0)
在 React 中,当满足以下两个条件之一时,组件会重新渲染:当组件的 props 发生变化时(即,当父组件传递新的 props 时),或者当状态更新时。在你的情况下,当你的组件第一次挂载时,你的 loadCurrentUser 被调用,它首先设置 state(isLoading = true),导致重新渲染,然后再次设置状态,导致再次重新渲染总共三个渲染,包括初始渲染。因此,如果您的日志显示相同数量的渲染,这是预期的行为,但如果重新渲染超过 3 次,请检查您的父组件以查看它是否正在更改传递给该组件的道具(我怀疑这是这里就是这种情况,因为 App 组件传统上是最顶层的组件,没有其他父组件。