2021년 2월 23일 복기(TIL REDUX)

Updating Arrays


const numbers = [1, 2, 3];

# Adding

const index = numbers.indexOf(2);
const added = [...numbers.slice(0, index), 4, ...numbers.slice(index)];

console.log(added);
[ 1, 4, 2, 3 ]

# Removing

const removed = numbers.filter((n) => n !== 2);

console.log(removed);
[ 1, 3 ]

# Updating

const updated = numbers.map((n) => (n === 2 ? 20 : n));

console.log(updated);
[ 1, 20, 3 ]

Enforcing Immutability

let book = { title: "Harry Potter" };

function publish(book) {
  book.isPublished = true;
}

publish(book);

console.log(book);

{ title: 'Harry Potter', isPublished: true }--
let book = Map({ title: "Harry Potter" });

console.log(book.get("title"));

Harry Potter

Immutable js

import { Map } from "immutable";

let book = Map({ title: "Harry Potter" });

function publish(book) {
  return book.set("isPublished", true);
}

book = publish(book);

console.log(book.toJS());

Immar.js

import { produce } from "immer";

let book = { title: "Harry Potter" };

function publish(book) {
  return produce(book, (draftBook) => {
    draftBook.isPublished = true;
  });
}

let updated = publish(book);

console.log(book); { title: 'Harry Potter' } 
console.log(updated); { title: 'Harry Potter', isPublished: true }

Redux Architectur

Designing the Store



bugs랑 currenUser 가 reducer

{
  bugs: [
    {
      id: 1,
      description: "",
      resolved: false,
    },
  ];
  currentUser: {
  }
}

Defining the Actions

{
    type: "ADD_BUG",
    description: "..."
}

{
  type: "bugAdded",
  payload : {
      id:1
  }
}

Creating a Reducer

/// []

let lastId = 0;

function reducer(state = [], action) {

  if (action.type === "bugAdded")
    return [
      ...state,
      {
        id: ++lastId,
        description: action.payload.description,
        resolved: false,
      },
    ];
  else if (actiony.type === "bugRemoved")
    return state.filter((bug) => bug.id !== action.payload.id);

  return state;
}

Refactoring

-reducer.js

export default function reducer(state = [], action) {
  switch (action.type) {
    case "bugAdded":
      return [
        ...state,
        {
          id: ++lastId,
          description: action.payload.description,
          resolved: false,
        },
      ];
    case "bugRemoved":
      return state.filter((bug) => bug.id !== action.payload.id);
    default:
      return state;
  }
}

Creating the Store

-store.js
import { createStore } from "redux";
import { reducer } from "./reducer";

const store = createStore(reducer);

export default store;

Dispatching Actions

좋은 웹페이지 즐겨찾기