我应该向哪个生命周期钩子发出请求并立即设置状态?

Which lifecycle hook should I make requests and immediately setState?

当我的组件安装时,我需要从 API 请求它的内容。在 docs:

componentDidMount() is invoked immediately after a component is mounted. Initialization that requires DOM nodes should go here. If you need to load data from a remote endpoint, this is a good place to instantiate the network request.

接下来是:

Calling setState() in this method will trigger an extra rendering (...) Use this pattern with caution because it often causes performance issues.

向 API 发出请求并立即设置响应的最佳做法是什么?

每当您触发 setState 时,您的组件将被重新渲染(无论生命周期事件如何)。

Use this pattern with caution...

例如,如果您在 componentWillReceiveProps 中触发 setState 而您没有正确处理未来的道具,您可能会陷入无限循环。

我的建议是坚持使用 componentDidMount 并在您的 api 请求完成后立即设置状态:

componentDidMount() {
  fetch('api-endpoint')
    .then(response => response.json())
    .then(result => this.setState({ stateProp: result }))
}

调用 API 并在收到响应后更新状态的最佳方法是 componentDidMount()componentWillMount()

哪一个可能取决于您要对来自 API 调用的数据执行的操作。如果您需要访问您的组件 DOM,则必须使用 componentDidMount()。也就是说,这些都不会使您免于额外的重新渲染,除非您的数据不需要设置为您的 state,在这种情况下您可以将其保存到 this

official documentation even states this, in this section:

componentDidMount() is invoked immediately after a component is mounted. Initialization that requires DOM nodes should go here. If you need to load data from a remote endpoint, this is a good place to instantiate the network request.

渲染调用之前 api:

  componentWillMount(){
     fetch(api)
        .then((response)=>{
         this.setState({data:response.data});
   })

}

渲染后调用 api:

  componentDidMount(){
     fetch(api)
        .then((response)=>{
         this.setState({data:response.data});
   })}

渲染调用道具数据之前:

  componentWillReceiveProps(){         
         this.setState({data:this.props.data});

}