LoginSignup
0
0

More than 1 year has passed since last update.

はじめてのReactおさわりお兄さんの成長記録#3 ~REST通信(GET)~

Last updated at Posted at 2021-09-30

目次

・シリーズ記事の紹介
・今回の焦点
・下準備
・実装
・今回のまとめ

シリーズ記事の紹介

はじめてのReactおさわりお兄さんの成長記録#1
https://qiita.com/T-AKIRA/items/a0e93631c4e3b56649d7
はじめてのReactおさわりお兄さんの成長記録#2
https://qiita.com/T-AKIRA/items/29a5cc0bf0233eba4b2e

今回の焦点

前回記事の末尾に記述したようにRest通信をReactでスッゾコラー

下準備

json-server を install せよ!

秒速でRest通信できるサーバーができるっていう最高にcrazyで
面倒くさがりの俺たちのすげぇ味方を紹介すっぞ!!
json-server
ででん!

npmコマンドはもうReact立ち上げたりしてるから
もちのろんで叩けるよね!いいね!じゃぁインストールするよ?いくよ?

C:\Users内緒>mkdir json_server

C:\Users内緒>cd json_server

C:\Users内緒\json_server>npm install -g json-server
C:\Users内緒\AppData\Roaming\npm\json-server -> C:\Users内緒\AppData\Roaming\npm\node_modules\json-server\lib\cli\bin.js
+ json-server@0.16.3
added 173 packages from 80 contributors in 42.609s

はい、どおん!!!!
ちょろりん

なんて簡単なんでしょう....
mkdir json_server部分はお好みでお願い申し上げます。

よっしゃ、jsonファイルをちょちょいと作って・・・
読みこめぇ!!!

C:\Users内緒\json_server>json-server --watch news.json

  \{^_^}/ hi!

  Loading news.json
  Done

  Resources
  http://localhost:3000/article

  Home
  http://localhost:3000

  Type s + enter at any time to create a snapshot of the database
  Watching...

GET /db 200 2.335 ms - 287
GET /__rules 404 2.671 ms - 2  ←←←これ何・・?そんなアクセスしとらんぞ?後回し
GET /article 200 29.434 ms - 258

きゃぁぁぁ!!素敵!!!( ^ω^)・・・ん?
Reactのデフォルトポートと被ってね?
試しにアクセスするとおさ兄のReactちゃんで作ったページが
でてこなくなっちまったじゃぁねえか!!こりゃいかん!

C:\Users内緒\json_server>json-server --port 3030  --watch news.json

  \{^_^}/ hi!

  Loading news.json
  Done

  Resources
  http://localhost:3030/article

  Home
  http://localhost:3030

  Type s + enter at any time to create a snapshot of the database
  Watching...

GET /db 200 5.592 ms - 287
GET /__rules 404 7.974 ms - 2
GET /article 200 25.572 ms - 258

おりゃあぁぁあああ、いったぁあああ!!!
ちゃんとReactページ復活じゃあああああ!!!(当然)
よし、ほんじゃココの情報をRestで取得して、表示したるでぇええ。。。。。

実装

んっっっっ!!!!!!??

取得した値どこにつめてどこに表示しよか・・・。
ほぁああああああああ
できました!!Stateに突っ込んでこねくり回すんですね!おりゃぁ

import React from 'react';

import './top.css'


export default class Top extends React.Component {
    constructor(props) {
        super(props);
        this.state = ({
            article: [],
        });
    };
    getJson = () => {
        const url = 'http://localhost:3030/article';
        fetch('http://localhost:3030/article')
            .then(response => response.json())
            .then(json => this.setState({
                article: json
            }))
            .catch(error => console.log(error));
    }

    newsList(list) {
        const articleList = list.map((article, index) => {
            return (
                <>
                    <span>
                        {article.date}
                    </span>
                    <br />
                    <span>
                        {article.summary}
                    </span>
                    <br />
                    <span>
                        {article.contents}
                    </span>
                    <br />
                </>
            );
        })
        return <div>{articleList}</div>;
    }

    render() {
        const menu_bar = (
            <nav>
                <ol>
                    <li> hoge</li>
                </ol>
            </nav>
        );
        const news_area = (
            <>
                <article>
                    <article>
                        {this.newsList(this.state.article)}
                    </article>
                </article>
                <button onClick={this.getJson}>
                    GET NEWS
                </button>
            </>
        );
        const sns_area = (
            <>
                <ol>
                    <li>facebook</li>
                    <li>instagram</li>
                </ol>
            </>
        );

        const message1 = <span> </span>;
        const message2 = <span> </span>;
        const message3 = <span> </span>;
        const message4 = <span> </span>;


        return (
            <>
                <div>
                    {menu_bar}
                </div>
                <hr />

                <div>
                    {message1}<br />
                    {message2}<br />
                    {message3}<br />
                    {message4}<br />
                </div>
                <hr />

                <div>
                    {news_area}
                    {sns_area}
                </div>
                <hr />
            </>
        );
    }
}

GET NEWSボタンを押下したらGET通信がとんでJsonをとってきます。
stateにjsonの格納先を用意しておきます。
(↑もっとええ方法があるんですかね・・・後で検討かなぁ)
setStateで取得した情報を保持させます。
stateの情報が変わったからNEWS内の表示が更新されます。
ちょっと不慣れな言語での通信処理だったので
手間取っちまったぜぃ・・・

でもでも、ボタン押さなきゃとってこないっていうより
表示時にとってくるようにしたいんだよね。。

ということでコード修正

import React from 'react';

import './top.css'


export default class Top extends React.Component {
    constructor(props) {
        super(props);
        this.state = ({
            article: [],
        });
    };

    newsList(list) {
        const articleList = list.map((article, index) => {
            return (
                <div key={index}>
                    <span>
                        {article.date}
                    </span>
                    <br />
                    <span>
                        {article.summary}
                    </span>
                    <br />
                    <span>
                        {article.contents}
                    </span>
                    <br />
                </div>
            );
        })
        return <div>{articleList}</div>;
    }

    async componentDidMount() {
        const url = 'http://localhost:3030/article';

        try {
            const response = await fetch(url);
            const json = await response.json();
            return this.setState({
                article: json
            });
        } catch (error) {
            return console.log(error);
        }
    }


    // ==========================================================

    render() {
        const menu_bar = (
            <nav>
                <ol>
                    <li> hoge</li>
                </ol>
            </nav>
        );
        const news_area = (
            <>
                <article>
                    <article>
                        {this.newsList(this.state.article)}
                    </article>
                </article>
            </>
        );
        const sns_area = (
            <>
                <ol>
                    <li>facebook</li>
                    <li>instagram</li>
                </ol>
            </>
        );

        const message1 = <span> </span>;
        const message2 = <span> </span>;
        const message3 = <span> </span>;
        const message4 = <span> </span>;


        return (
            <>
                <div>
                    {menu_bar}
                </div>
                <hr />

                <div>
                    {message1}<br />
                    {message2}<br />
                    {message3}<br />
                    {message4}<br />
                </div>
                <hr />

                <div>
                    {news_area}
                    {sns_area}
                </div>
                <hr />
            </>
        );
    }
}

主な変更として

                <button onClick={this.getJson}>
                    GET NEWS
                </button>

を削り、getJsonメソッド?をcomponentDidMountメソッド内に
移動しました!
componentDidMountはrender後に呼び出されるメソッドらしく、
Newsの内容は後からピロってきても良いかと思い、そうしました!

嘘です

課題から目を一瞬背けました。
render()にいれてたんですよ、最初。
そしたらjson_serverに死ぬほどGET送ってきやがったんですよ・・・ナンデェ

ということで今回の課題はここまで。
とりあえず目標達成!!お疲れ様です!

renderにメソッドいれたら死ぬほどリクエスト送る問題は
別途
課題に足して調査しよう!

今回のまとめ

・json-server有能でやんす
・fetch(REST通信)でとってきたJsonはstateに突っ込みゃあいいんだよ
・初期表示で情報とってくるときにrender()関数に突っ込んだら無限通信するから気をつけよ

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0