小编Vim*_*din的帖子

为什么我的 React 组件渲染多次

我正在尝试在 App.js 中为经过身份验证的用户添加受保护的路由,但反应元素被渲染多次。下面是我的 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" …
Run Code Online (Sandbox Code Playgroud)

reactjs

5
推荐指数
1
解决办法
1万
查看次数

标签 统计

reactjs ×1