Redux

유관희·2022년 10월 28일
0

→ Open in Slid


‏‏‎ ‎

‏‏‎ ‎

‏‏‎ ‎

‏‏‎ ‎

‏‏‎ ‎

store.subscribe(render);

에서 state 값이 바뀔때 마다 render 를 바꾸려면 store.subscribe 안에 render를 넣는다.

‏‏‎ ‎

<form onsubmit="
	//...
	store.dispatch({type:'create',
         payload{title:title,desc:desc}});
">
//Submit 버튼을 누르면 객체인 정보가 dispatch 한다. type이 중요!

‏‏‎ ‎

‏‏‎ ‎

function reducer(state, action){
  if(state === undefined){
    return {color:'yellow'}
  }
}
var store = Redux.createStore(reducer);
// Redux를 사용하기 위해서는 제일 처음 store를 만들어야 한다. 
// Redux.createStore 로 store를 만들어 준 다음 store 안에 reducer를 
// 넣어 주어야 한다. reducer에는 2가지 인자를 받는데 state, action 이다.
// 우선 제일 처음 redux를 사용할때 state 값의 초기값이 undefined 일 수가 
// 있으므로 초기값을 잡아둔다. 여기서는  {color:'yellow'}인 객체로 주었다.
// 이모든 값을 변수 store 에 넣어 주었다.
// 이 store의 값을 보기 위해서는 호출해야 하는데 이때 getState()를 쓴다.

console.log(store.getState());


‏‏‎ ‎

* state를 변형시키기위해 dispatch 이용

<input type='button' value='fire' onClick="
	store.dispatch({type:'CHANGE_COLOR',color:'red'})
">
//dispatch는 reducer 에게 state,action 값을 주는 것이다. 

* reducer 를 사용할때 state를 retodo 같은 것을 이용할때 복제하는 것이 훨씬 좋다.

복제 방법은...

Object.assign({}, {name:'egoing'},{city:'seoul'})
// 객체를 복제 할때는 assign을 쓴다. 이것을 실행하면

==> {name:'egoing', city:'seoul'}
// 결과 값은 하나의 객체로 나온다. 

----------------------------------------------------------
var newState;
if(action.type === 'CHANGE_COLOR'){
  newState = Object.assign({},state, {color:'red'})
}
return newStae;

// 새로운 변수 newState 에 assign을 이용한 값을 넣고 이 복제 값을 return
한다.

* 이제 인풋을 이용. dispatch 를 이용한다.

<input type='button' value='fire' onClick='
	store.dispatch({type:'CHANGE_COLOR', color:'red'})
'>
// input을 통해 disptch 의 객체의 값을 store로 보낸다.

store.subscribe(red);
// dispatch를 통해 store로 보낸 값이 변한 red 값을 
// subscribe(red)를 통해 red 값이 변할때마다 subscribe 한다.

‏‏‎ ‎

Redux dev 사용하기

 let store = Redux.createStore(
                reducer,
                window.__REDUX_DEVTOOLS_EXTENSION__ &&
                    window.__REDUX_DEVTOOLS_EXTENSION__()
            );

‏‏‎ ‎

profile
안녕하세요~

0개의 댓글