FrontEnd/Redux

[Redux] createStore part 2 배열 사용해보기

무무둥 2023. 3. 9. 00:50

이전에 했던 것과 같이 import를 해준다.

import { createStore } from "redux";

 

state값을 배열로 초기화 해준다. 여기까지는 특별할 것이 없다.

const reducer = (state = [], action) => {
	return state;
}
const store = createStore(reducer);

 

action을 통해 state 값을 변경해 줄 것인데 여기서 일반 string이나 number 형식과 차이가 발생한다.

redux 공식 사이트 안내

중요!!! state의 값은 read only 이다.

 

state의 값을 직접 변경해서는 안된다.

XXXXXXXXXXX state.push() XXXXXXXXXXX 와 같은 작업을 해서는 안된다. 절대로!

const reducer = (state = [], action) => {
	switch(action.type){
      case "ADD":
        return [...state, action.text];
      default:
        return state;
    }
}
const store = createStore(reducer);
store.subscribe(() => console.log(store.getState()));

store.dispatch({ type: "ADD", text: "hello" });
store.dispatch({ type: "ADD", text: "world" });

만약 state.push() 와 같은 기능을 원한다면 위와 같이 작성해야 한다.

결과 출력값

 

'FrontEnd > Redux' 카테고리의 다른 글

[Redux] createStore 사용해보기  (0) 2023.03.08