Udemy-React-Course
  • Introduction
  • CodeSandbox で作る開発環境
    • CodeSandbox を使う利点
    • GitHub との連携
    • CodeSandbox の構造
  • 初めての React App
    • 最小限の React アプリケーションの実装
    • JSX と React Element
    • ES2015 のアロー関数について
    • React でアロー関数を使用する
    • 初めての React Component
    • ES2015 の import / export
    • export default
    • 2章の復習
  • State を持ったコンポーネント
    • State とは何か
    • ES2015 の class
    • React Class Component の書き方
    • click された時に setState で state を変更する
    • H20 Component 1
    • H20 Component 2
    • H20 Component 3
    • H20 Component 4
    • map と filter
    • map と filter の実践
  • 実践:TodoApp の作成
    • TodoApp の作成
  • 非同期処理, Promise, Ajax
    • HTTP プロトコルと AJAX
    • 非同期処理と Promise
    • JSON を取得し、その内容をレンダリングする React App の作成
  • 実践:API を叩く App
    • Giphy API を使用して、GIF画像検索する React App の作成
  • Redux の導入
    • Redux の概要
    • createStore で store を作る
    • Provider と Connect / store を React で使用する
    • Redux の全体像の確認
    • Presentational Component と Container Component
    • Action Creator
    • Combine Reducer
  • Redux-thunk を用いた非同期処理
    • Redux-thunk で非同期にアクションを発行する
    • Promise を Redux-thunk 上で活用する
  • React + Redux + Redux を用いた Giphy App
    • store を作る
    • Component に store を connect する
    • Search コンポーネントの作成
    • GiphyAPI を叩くメソッドの作成と Redux-thunk を使った非同期処理
    • 改善
  • 補足資料
    • App = ({name}) => name 型のシンタックス / Destructuring assignment
    • Class Component と Functional Component の使いわけ
  • 参考資料と謝辞
Powered by GitBook
On this page
  • Action Creator の中で非同期処理がうまく書けない… Redux-thunk を使う
  • うまくいかない例
  • index.js で redux-thunk を middleWare として適用する
  • 重要 関数を返すアクションクリエイターを作る
  • コンポーネント、コネクトの修正
  1. Redux-thunk を用いた非同期処理

Redux-thunk で非同期にアクションを発行する

PreviousRedux-thunk を用いた非同期処理NextPromise を Redux-thunk 上で活用する

Last updated 7 years ago

Action Creator の中で非同期処理がうまく書けない… Redux-thunk を使う

次のように Action Creator の中でアクションを非同期に返しても、うまくいきません。ですので 「Redux-thunk」 をミドルウェアとして使用する必要があります。

うまくいかない例

actions/index.js

export const asyncMinus = num => {
  setTimeout(() => {
    return { type: "MINUS", payload: { num: num } };
  }, 1000);
};

index.js で redux-thunk を middleWare として適用する

index.js

import React from "react";
import { render } from "react-dom";

// store に middleWare を適用するための関数
// applyMiddleware を import する
import { createStore, applyMiddleware } from "redux";
import rootReducer from "./reducers";

import { Provider } from "react-redux";

import App from "./containers/App";

// redux-thunk
import thunk from "redux-thunk";

// 後々複数の middleWare を適用できるように配列に入れる
const middleWares = [thunk];

// createStore の第二引数に、
// applyMiddleware() を使って、middleWare を適用する
const store = createStore(rootReducer, applyMiddleware(...middleWares));

render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById("root")
);

重要 関数を返すアクションクリエイターを作る

actions/index.js

これは Action Creator ですが、 action そのものを返すのではなく 、 「内部でアクションを dispatch する 関数 」を返してあげます。関数が dispatch されてくると、middleWare に使われている redux-thunk が見つけて、対応してくれます。

// (dispatch) => {} という関数を返すようにする
// この中で dispatch(action) をすればよい
export const asyncMinus = num => {
  return dispatch => {
    setTimeout(() => {
      dispatch({ type: "MINUS", payload: { num: num } });
    }, 1000);
  };
};

コンポーネント、コネクトの修正

containers/App.js

import App from "../components/App";
import { connect } from "react-redux";

// 作った action である asyncMinus を読み込む
import { minus, plus, asyncMinus } from "../actions";

const mapStateToProps = state => {
  return {
    number: state.number,
    day: state.day,
    title: state.title
  };
};

const mapDispatchToProps = dispatch => {
  return {
    plus: num => {
      dispatch(plus(num));
    },
    minus: num => {
      dispatch(minus(num));
    },
    asyncMinus: num => {
      // 渡す
      dispatch(asyncMinus(num));
    }
  };
};

export default connect(mapStateToProps, mapDispatchToProps)(App);

components/App.js

import React from "react";

// asyncMinus を受け取る
const App = ({ number, day, title, plus, minus, asyncMinus }) => (
  <div>
    <h2>
      {title} {number} {day}
    </h2>
    <button
      onClick={() => {
        plus(10);
      }}
    >
      + 10
    </button>
    <button
      onClick={() => {
        minus(10);
      }}
    >
      - 10
    </button>
    <button
      onClick={() => {
        // 実行する
        asyncMinus(10);
      }}
    >
      async - 10
    </button>
  </div>
);

export default App;
https://codesandbox.io/s/ovv2o75mr5