React(생활코딩)_18일차_로딩중기능구현

Lina Hongbi Ko·2023년 10월 10일
0

React_생활코딩

목록 보기
19/23

저번시간에는 프레젠테이셔널 컴포넌트와 컨테이너 컴포넌트를 분리하고 XML과 JSON의 개념정리를 다시 한번 해보았다.

오늘은 통신을 할때 응답시간이 길어질 때 '로딩중'이라고 알려주는 기능을 책을 통해 실습하려고 한다.

✏️ 로딩중 기능 구현하기

서버와 통신하는 시간이 길어지면 사용자가 답답해할 수 있기 때문에, 현재 로딩중 이라는 것을 알려주는 UI가 종종 필요하다.

생코님책에서는 이 기능을 구현하기 위한 실습을 진행했는데 오늘은 그 실습을 따라 해보려고 한다.

일단,
로딩이 빠른 경우 구현한 기능을 제대로 확인 할 수 없기 때문에 네트워크 속도를 늦춰보자.

개발자 도구의 네트워크 설정으로 들어가서 'Slow 3G'라고 설정한 다음 구현해보자.

책에서 나온 코드를 작성해보면,

// ReactAjax.js 파일

import React, { Component } from 'react';

class Nav extends Component {
	render(){
    	let listTag = [];
        for(let i = 0; i < this.props.list.length; i++) {
        	const li = this.props.list[i];
            listTag.push(<li key={li.id}><a href={li.id} data-id={li.id} onClick={function(e){
            	e.preventDefault();
                this.props.onClick(e.target.dataset.id);
            }.bind(this)}></a>{li.title}</li>)
        }
        return(
        	<nav>{listTag}</nav>
        );
    }
}

class Article extends Component {
	render() {
    	return(
        	<article>
            	<h2>{this.props.title}</h2>
                {this.props.desc}
            </article>
        );
    }
}

class NowLoading extends Component {
	render(){
    	return(
        	<div>Now Loading....</div>
        );
    }
}

class ReactAjax extends Component {
	state = {
    	article:{
        	item:{title:"Welcome", desc:"Hello, React & Ajax"},
            isLoading: false,
        },
        list:{
        	items: [],
            isLoading: false,
        }
    }
    
    componentDidMount() {
    	let newList = Object.assign({}, this.state.list, {isLoading:true});
        this.setState({list:newList});
        fetch('list.json')
        .then(function(result){
        	return result.json();
        })
        .then(function(json){
        	this.setState({ list:{
            	items: json,
                isLoading: false
            }});
        }.bind(this));
    }
    
    render(){
    	let NavTag = null;
        if(this.state.list.isLoading) {
        	NavTag = <NowLoading></NowLoading>
        } else {
        	NavTag = <Nav list={this.state.list.items} onClick={function(id){
            	let newArticle = Object.assign({}, this.state.article, {isLoading:true});
                this.setState({article:newArticle});
                fetch(id+'.json')
                .then(function(result){
                	return result.json();
                })
                .then(function(json){
                	this.setState({
                    	article:{
                        	item:{
                            	title:json.title,
                                desc:json.desc
                            },
                        	isLoading: false
                        }
                    })
                 }.bind(this));
            }.bind(this)}></Nav>
        }
        
        let ArticleTag = null;
        if(this.state.article.isLoading) {
        		ArticleTag = <NowLoading></NowLoading>
            } else {
        		ArticleTag = <Article title={this.state.article.item.title} desc={this.state.article.item.desc}></Article>
       		}
        
        return(
        	<div className="ReactAjax">
            	<h1>WEB</h1>
                {NavTag}
                {ArticleTag}
            </div>
        );
    }
}

export default ReactAjax;

요로코럼 작성하였다.

이 코드를 설명하자면,

일단 ReactAjax 컴포넌트의 state 구조가 바뀌었다. isLoading이 추가 되었고, article과 list는 item과 state.article.item으로, state.list.items로 바꿔주었다.

article과 list의 구조가 바뀌었기 때문에 componentDidMount 메소드의 setState메소드도 변경된 state 구조에 맞게 변경하고, isLoading 값은 로드가 시작될때 true였다가 로드가 끝나면 false로 바뀌도록 하였다. 따라서 isLoading 값이 true일때는 NowLoading 컴포넌트를 보여주고, false인 경우에는 기존 컴포넌트를 보여주도록 하였다.

요로코롬하고 결과화면을 보면,

이렇게 나온다. 항목을 하나하나 클릭할때마다 로드가 될때 Nowloading 컴포넌트가 나타나는 것을 볼 수 있고, 로드가 완료되면 Article의 내용이 출력되는 것을 볼 수 있다.

그리고 각 로딩은 각자의 컴포넌트에 종속되어 있기 때문에 여러개의 로딩이 동시에 진행되는것은 별도의 문제가 없다고 한다.

이렇게 로딩을 구현하는 실습을 생코님 책을 통해 진행해보았다.

:)


출처

생활코딩! 리액트 프로그래밍 책

profile
프론트엔드개발자가 되고 싶어서 열심히 땅굴 파는 자

0개의 댓글