非同期処理を使い始めたのでReactのライフサイクルとfetchを試す。
6 min readJan 9, 2019
【所要時間】
【概要】
- Reactのライフサイクルメソッド(componentWillMountとか)とfetchを使ってみる。
- CodeSandbox
https://codesandbox.io/s/1y0k12221j
【要約・学んだこと】
Reactのライフサイクルメソッドを使ってみる。
今もいい使い方が思い浮かばなかったが、実際に使う場面では
- データを取得→取得したデータを表示
- まずテキストを表示→その後データを取得
などの使い方が多いと思われる。
今回は
- initial stateに
txt: ”初期画面”, backGround: “yellow”(背景色として表示される)
を持たせた。
Reactではinital stateを取得した次にcomponentWillMountを読み込み、renderを読み込む。そして最後にcomponentDidMountを読み込む。
- componentWillMountでは
txt: “読み込み中”, backGround: “white”
を読み込み、alertを出す。初期画面が見えるようにsetTimeoutで2000mm秒待たせている。
- componentDidMountでは
txt: “読み込み完了”, bkImg: `url(${img}` (背景画像として表示される。)
こちらもsetTimeoutで2000mm秒待たせている。
背景画像の読み込みには多少の時間がかかるが重要ではないので、コンテンツを先に読み込む方がいいはず。
ファイルの読み込みなどに時間がかかる場合、取得する順番が重要になることもあると思われる。
import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";
import img from "./img.jpg";class App extends React.Component {
constructor(props) {
super(props);
this.state = {
txt: "初期画面",
fromTxt: "",
backGround: "yellow",
bkImg: ""
};
}clickHandler() {
fetch("https://holidays-jp.github.io/api/v1/date.json")
.then(response => {
return response.json();
})
.then(text => {
this.setState({
txt: "clicked",
fromTxt: JSON.stringify(text)
});
})
.catch(
this.setState({
fromTxt: "ファイルを取得できませんでした。"
})
);
}componentWillMount() {
setTimeout(() => {
this.setState({
txt: "読み込み中",
backGround: "white"
});
// alert("loading");
}, 2000);
}componentDidMount() {
setTimeout(() => {
this.setState({
txt: "読み込み完了",
bkImg: `url(${img}`
});
}, 2000);
}render() {
return (
<div
className="App"
style={{
backgroundColor: this.state.backGround,
backgroundImage: this.state.bkImg,
color: "red"
}}
>
<button onClick={() => this.clickHandler()}>get txt</button>
<p>{this.state.txt}</p>
<p>{this.state.fromTxt}</p>
</div>
);
}
}
fetchを試す。
外部ファイルを取得するpromiseをつかった実装。フリーで公開されていた祝日一覧を取得し、表示してみる。
fetch("https://holidays-jp.github.io/api/v1/date.json")
.then(response => {
return response.json();
})
.then(text => {
this.setState({
txt: "clicked",
fromTxt: JSON.stringify(text)
});
})
.catch(
this.setState({
fromTxt: "ファイルを取得できませんでした。"
})
);
promise,thenを使っており、データを取得した後にsetStateする。
試しにthenに存在しない変数を入れてみると
catchの内容が反映された。
【わからなかったこと】
- ローカルにあるjsonを取得しようとしたがやり方がわからなかった。
- 関係ないがwindowsでgitがうまく使えなかった。
【感想】
どこが難しいとかではないがいいアイデアがないので、チュートリアルがあればやってみたい。