Entoverse

Reactのこと

AJAX APIs JSON受信

AJAXコールを作成する

Reactでは、AJAXライブラリに関してAxiosjQuery AJAXブラウザ組み込みのwindow.fetchなど使うことが可能です。 componentDidMountライフサイクルメソッドで、AJAX呼び出しを使用してデータを入力する必要があります。 データが取得されたときにsetStateを使用してコンポーネントを更新できるようにするためです。

{
  "hoge": 1010,
  "hoge2": "鉄人"
}

上記のJSONをfetch()で取得するコンポーネントを作成します。

import React, { Component } from 'react';
import Button from '@material-ui/core/Button';
import Typography from '@material-ui/core/Typography';

class CA extends Component
{
    state = 
    {
        test: 0,
        Button1: "ボタン",
        Text11: "",
        hoge:null,
        hoge2:null
    };

    Button1Click(){
      this.setState({
          b1 : "接続開始",test:1 
      });
      fetch("https://URL")
      .then(res => res.json() )
      .then((result)=>{
          this.setState({Button1:"接続成功", hoge:result.hoge, hoge2: result.hoge2} );
      },(error)=>{
          this.setState({Button1:"失敗です"});
      } );
    }

    render()
    {
        return (
            <div>
                <Button onClick={()=>this.Button1Click()} color="primary">
                    {this.state.Button1}{this.props.Text11}
                </Button>
                <Typography>{ this.state.hoge }</Typography>
                <Typography>{ this.state.hoge2 }</Typography>
            </div>
        );
    }
}

export default CA;

実行するとこのような感じです。
f:id:mojeld:20180831111217g:plain

AJAX and APIs – React