Fetching data from an Api with React

ComponentDidMount:
get code from somewhere as your component can do what it should do

right here is where we would get an kind of data that required for this component to display or to do

.png

javaScript built-in function: fetch---nice easy promise way to perform http request
fecth - api - promise

image.png

下一步,数据拿回来了,怎么渲染页面呢?

Save data: The way we save data within a component is by its state, ant time we want to change the state, we are going to call this.setState()

在fetch的promise最后一步通过setState改变state,设置返回的数据。前提是你要在constructor里面初始化代表这个数据的变量。我们知道返回的json数据是一个object,所以初始化采用character:{}。然后在下面render里面利用state进行渲染。

image.png

Loading之后显示data的完整逻辑,要好好利用this.state和this.setState当你想要改变数据或者状态时:(注意对于loading的几次改变,当要显示数据之前,把loading变成false,因为你不会想要一直出现loading而不出现数据)


image.png
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容