为什么异步请求应该在componentDidMount中而不是在ReactJS中的getInitialState中进行? [英] Why async requests should be made in componentDidMount instead of getInitialState in ReactJS?

查看:103
本文介绍了为什么异步请求应该在componentDidMount中而不是在ReactJS中的getInitialState中进行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

React文档的这个页面显示应该在<$中使用异步请求的数据c $ c> componentDidMount 事件,而 getInitialState 将状态对象初始化为默认的状态。

This page of React's docs shows that async requested data should be consumed in the componentDidMount event, while getInitialState initialize the state object to a default empty state.

这有什么理由吗?也许getInitialState不会这样做或有不同的目的?这是由于图书馆的一些内部逻辑吗?

Is there a reason for that? Maybe getInitialState is not expected to do this or has a different purpose? Is it due to some internal logic of the library?

注意到版主和回答者:这不是一个基于意见的问题:如果存在某种原因,这将是答案,但是,对我的问题的一个好的,正确的答案也可以是不,没有任何特别的理由,做任何你感觉更好的事情

推荐答案

getInitialState 应该是一个纯粹的道具功能(虽然它们经常不被使用)。换句话说,使用相同的道具getInitialState应该返回相同的数据。

getInitialState should be a pure function of props (though they often aren't used). In other words, with the same props getInitialState should return the same data.

componentDidMount 被允许具有动态行为,并导致副作用,如dom操作和ajax请求(这是它的主要目的)。

componentDidMount is allowed to have dynamic behavior, and cause side effects such as dom manipulation and ajax requests (that's the main intention of it).

处理此问题的常用方法是提前返回空div,加载消息,< div> Loading< / div> )或加载指标(例如 spinkit )。

A common way to handle this is with an early return of either an empty div, loading message, <div>Loading</div>), or loading indicator (e.g. spinkit).

在第一次渲染时,将显示微调器,然后最终使用数据更新状态,并且可以运行渲染的主要部分。

On first render the spinner will be shown, and then eventually state is updated with data and the main part of render can be run.

render: function(){
   // while loading
   if (!this.state.data){
     return <div className="spinner"></div>
   }

   // loaded, you can use this.state.data here
   return <div>...</div>
}

这篇关于为什么异步请求应该在componentDidMount中而不是在ReactJS中的getInitialState中进行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆