react redux 같이 쓰기 위한 스크립트
<script src="https://www.unpkg.com/react-redux@8.0.5/dist/react-redux.js"></script>
사용할 기능 꺼내오기
const { createStore } = Redux;
const { Provider, useSelector, useDispatch } = ReactRedux;
const initialState = 0;
createStore
: Redux의 기능. store(저장소)를 만듦
//리듀서 함수를 이용해서 스토어 생성
const store = createStore(reducer);
useSelector
: store로부터 state를 꺼내옴
반드시 인자로 state를 매개변수로 하는 함수를 콜백으로 전달해야한다.
여러개의 값이 관리되고있다면 'state.자료명'으로 꺼내올 수 있다.
지금은 1개의 값만 관리되고 있기때문에 state로 적어줌
const count = useSelector((state) => state);
useDispatch
: reducer 함수 호출
const dispatch = useDispatch();
const incrementCount = () => {
dispatch({
type : 'INCREMENT',
payload : {
incrementValue : 1
}
});
};
Provider
: store를 props 형태로 전달하면 하위 컴포넌트는 store를 자동으로 구독
ReactDOM.createRoot(document.getElementById('root')).render(
<Provider store={store}>
<App/>
</Provider>
);
state를 변경하기 위한 리듀서 함수의 정의
action은 dispatch를 호출하는 쪽에서 전달해주는 객체로
행위의 종류(type)와 state 변경에 대한 내용(payload)을 담고 있다.
function reducer (state = initialState, action){
const { payload } = action;
switch(action.type) {
case 'INCREMENT' :
return state + payload.incrementValue;
case 'DECREMENT' :
return state - payload.decrementValue;
default :
return state;
}
}
state를 변경하기 위한 리듀서 함수의 정의
action은 dispatch를 호출하는 쪽에서 전달해주는 객체로
행위의 종류(type)와 state 변경에 대한 내용(payload)을 담고 있다.
function reducer (state = initialState, action){
const { payload } = action;
switch(action.type) {
case 'INCREMENT' :
return state + payload.incrementValue;
case 'DECREMENT' :
return state - payload.decrementValue;
default :
return state;
}
}