본문 바로가기
React를 같이 배워보자

React21일차-middleware

by 멈추지않아 2022. 2. 10.

저번게시물 폴더를 다시열어주시고  npm start 해주시고 콘솔창열어주세요

redux/store.js

import { applyMiddleware, createStore } from "redux";
import fileReducer from "./reducer";
function middleware1(store) {
  console.log("1-1");
  return (next) => {
    console.log("1-2");
    return (action) => {
      console.log("1-3", next);
      const returnvalue = next(action);
      console.log("1-4");
      return returnvalue;
    };
  };
}
function middleware2(store) {
  console.log("2-1");
  return (next) => {
    console.log("2-2");
    return (action) => {
      console.log("2-3");
      const returnvalue = next(action);
      console.log("2-4");
      return returnvalue;
    };
  };
}
const store = createStore(
  fileReducer,
  applyMiddleware(middleware1, middleware2)
);

export default store;
이렇게 변경 하고 콘솔창을 보면

기본적으로 순서대로 한번씩 실행되고  12는 dispatch전에 34는 후에 일어나는것을 볼수 있다.

이걸이용해서 dispatch전에 추가 기능을  수행하게 할수 있다.

 

그럼 이번에는 npm i redux-thunk 설치해주세요

그리고 store.js

import { applyMiddleware, createStore } from "redux";
import thunk from "redux-thunk";
import fileReducer from "./reducer";

const store = createStore(fileReducer, applyMiddleware(thunk));

export default store;

이렇게 변경해주세요

redux/action.js

export function adduser() {
  return (dispatch) => {
    const res = [
      { name: "mark1", id: 1 },
      { name: "mark2", id: 2 },
      { name: "mark3", id: 3 },
      { name: "mark4", id: 4 },
      { name: "mark5", id: 5 },
    ];
    dispatch(indata(res));
    console.log("adduser");
  };
}

추가

adduser를 dispatch의 일부분으로 만들었습니다.

그럼 user.js가서 dispatch처럼 사용하게

import Liststore from "../hook/liststore";
import addstore from "../hook/addstore";
import { adduser } from "../redux/action";

export default function List() {
  const state = Liststore();

  const dispatch = addstore();
  dispatch(adduser());

  return (
    <div>
      {state.user.data.map((p) => (
        <li key={p.id}>{p.name}</li>
      ))}
    </div>
  );
}
이렇게 수정해주세요

그럼 이렇게 잘나오는것을 확인할수 있습니다.

오늘도 다들 고생 많으셧습니다.

'React를 같이 배워보자' 카테고리의 다른 글

React22일차-promise and redux dev tools  (0) 2022.02.11
React22일차-Duckspattern  (0) 2022.02.11
React21일차-Redux추가  (0) 2022.02.10
React20일차-Redux를 react와 연결  (0) 2022.02.09
React19일차-Redux  (0) 2022.02.08