質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.50%
Redux

Reduxは、JavaScriptアプリケーションの状態を管理するためのオープンソースライブラリです。ReactやAngularで一般的にユーザーインターフェイスの構築に利用されます。

React.js

Reactは、アプリケーションのインターフェースを構築するためのオープンソースJavaScriptライブラリです。

Q&A

0回答

407閲覧

redux-thunkのサンプルコード

megane-taro

総合スコア1

Redux

Reduxは、JavaScriptアプリケーションの状態を管理するためのオープンソースライブラリです。ReactやAngularで一般的にユーザーインターフェイスの構築に利用されます。

React.js

Reactは、アプリケーションのインターフェースを構築するためのオープンソースJavaScriptライブラリです。

0グッド

0クリップ

投稿2021/12/02 14:53

https://reffect.co.jp/react/react-redux-for-beginner#redux-thunk
↑こちらのページ下部「redux-thunkを利用した非同期処理」の処理でよく理解できない箇所があります。

store/index.jsのソースコードの一部

export const getPosts = () => { return async (【dispatch】) => { const res = await fetch('https://jsonplaceholder.typicode.com/posts'); const data = await res.json(); dispatch({ type: 'GET_POST_DATA', payload: data, }); }; };

【】で囲まれた「dispatch」はどこから出てきたものなのでしょうか?
部分的だとわからないと思うので、ソースコード全容を下記します。

親コンポーネント(App.js)

import store from "./store/index"; import { Provider } from "react-redux"; import ChildIndex from "./components/Child"; const App = () => { return ( <> <Provider store={store}> <ChildIndex /> </Provider> </> ); }; export default App;

子コンポーネント(components/Child.js)

import { useEffect } from "react"; import { useSelector, useDispatch } from "react-redux"; import { getPosts } from "../store/index"; const Child= () => { const props = useSelector((state) => state.reducer.payload); const dispatch = useDispatch(); useEffect(() => { dispatch(getPosts()); }, [dispatch]); return ( <> text </> ); }; export default Child;

store(store/index.js)

import { createStore, applyMiddleware } from "redux"; import thunk from "redux-thunk"; const initialState = { payload: [], }; const reducer = (state = initialState, action) => { switch (action.type) { case "success": return { ...state, payload: action.payload, }; default: return state; } }; const store = createStore( reducer ); export const getPosts = () => { return async (【dispatch】) => { const res = await fetch("https://jsonplaceholder.typicode.com/posts"); const data = await res.json(); dispatch({ type: "success", payload: data, }); }; }; export default store;

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

まだ回答がついていません

会員登録して回答してみよう

アカウントをお持ちの方は

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.50%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問