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;
あなたの回答
tips
プレビュー