참고
React-Redux
NOTE
redux 자체는 독립적인 라이브러리이다. react-redux는 react와 redux를 연결해주는 라이브러리이다.
•
모든 종류의 UI 프레임 워크와 함께 Redux를 사용하는 경우 일반적으로 UI 코드에서 ‘Ui 바인딩’ 라이브러리를 사용하여 Redux와 UI 프레임워크를 연결한다
•
React Redux는 React용 공식 Redux UI 바인딩 라이브러리다.
const counterReducer = (state = {counter: 0, showCounter: true}, action) => {
const initialState = {counter: 0, showCounter: true}
if(action.type === INCREMENT){
return{
counter: state.counter + 1,
showCounter: state.showCounter
}
}
if(action.type === 'increase'){
return{
counter: state.counter + action.amount,
showCounter: state.showCounter
}
}
if (action.type === 'decrement') {
return{
counter: state.counter - 1,
showCounter: state.showCounter
}
}
if (action.type === 'toggle') {
return{
counter: state.counter,
showCounter: !state.showCounter
}
}
return state;
}
const store = createStore(counterReducer);
export default store;
JavaScript
복사
사용 store
Provider
NOTE
Redux를 App.js에 연결하기 위해 index.js로 가서 감싸준다.
const counterReducer = (state = {counter: 0, showCounter: true}, action) => {
const initialState = {counter: 0, showCounter: true}
if (action.type === 'decrement') {
return{
counter: state.counter - 1,
showCounter: state.showCounter
}
}
return state;
}
const store = createStore(counterReducer);
JavaScript
복사
store
import React from 'react';
import ReactDOM from 'react-dom/client';
import {Provider} from 'react-redux'
import App from './App';
import store from './store/index'
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Provider store={store}><App/></Provider>);
JavaScript
복사
index.js
useSelector
NOTE
useSelector를 사용하면 상태값을 쉽게 가져올 수 있다.
import { useSelector } from 'react-redux';
const fruitList = useSelector(state => state.fruit);
// useSelector의 사용법
JavaScript
복사
redux의 state를 받아올 수 있다
useDispatch
NOTE
useDispatch를 사용하면 리덕스에 저장된 상태값을 변경시킬 수 있다!
import { useDispatch } from 'react-redux';
cosnt dispatch = useDispatch(); // dispatch로 재선언하여 사용한다.
// 사용
const incrementHandler = () => {
dispatch({ type: "increment" });
};
JavaScript
복사
redux의 action을 사용할 수 있다.
const counterReducer = (state = {counter: 0, showCounter: true}, action) => {
// reducer의 action
if (action.type === "increment") {
return {
counter: state.counter + 1,
showCounter: state.showCounter, //기존의 showCounter를 벨류를 취할 것
};
}
// ...
}
JavaScript
복사
reducer에서 action 분기
•
state는 변경되면 안되기 떄문에, 항상 action을 통해서 새로운 객체나 배열을 만들어서 return을 해줘야한다!