React ComponentDidMount 被多次调用

React ComponentDidMount being called multiple times

我正在尝试在 AccountItem.js 内部进行提取 api 调用,如下所示:

componentDidMount() {
    // I am calling console.log("item mounted"); here
    var url = "myurl" + this.props.portalId;
    fetch(url)
    .then(res => res.json())
    .then(data => this.setState({account: data.Items}));
}

然后在我的 Home.js 中呈现:

componentDidMount() {
   console.log("home mounted");
}
render() {
    return (
      <div>
        Account Dashboard
        <AccountItem portalId={this.props.portalId}/>
      </div>
    );
  }
}

我正在将我的提取记录到控制台,它被调用了三次。流程是我在登录页面上(加载时安装一次),我登录后将我重定向到本身呈现的主页。此时在我的控制台中我看到:

Login mounted // initial load, now I click login Login mounted // Renders again then redirects to homepage Item mounted Home mounted Item mounted Home mounted Item mounted // Why is this happening 3 times?

我是 React 新手,如果您需要更多信息,请告诉我。

好的,问题出在我的路由器上,我正在渲染这个:

<BrowserRouter>
                <div>
                    // Other routes here
                        <this.PrivateRoute path="/home" exact component={<Home .... />} />
                    </Switch>
                </div>
            </BrowserRouter>

我的私人路线是:

PrivateRoute = ({ component: Component, ...rest }) => (
                <Route {...rest} render={() => (
                    this.state.isAuthenticated
                    ? <Component {...this.props} portalId={this.state.portalId}/>
                    : <Redirect to="/" />
                )}/> 
            )

所以这个家被渲染了多次。我只是将路由器内的 <Home /> 换成 {Home}