npm i redux react-redux @reduxjs/toolkit
import {configureStore} from "@reduxjs/toolkit";
import { Provider } from "react-redux";
configureStore : store 생성 함수.
Provider: 리액트 App.js 에 Store 를 손쉽게 연동 할 수 있도록 도와주는 컴포넌트
//index.js
//초기값
const intialState ={
number:0,
}
// Reducer 정의 : 변화를 일으키는 함수
const reducer = ( state = initialState,action) =>{
switch (action.type){
case"INCREMENT":
return{number:state.number +1};
case"DECREMENt":
return{number:state.number -1};
default:
return state;
}
}
const store = configureStore({ reducer: reducer }, composeWithDevTools());
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<Provider store={store}>
<App4 />
</Provider>
);
npm i redux-devtools-extension
를 설치해야 Chrome 에서 확장프로그램으로 redux를 확인 할 수 있다.//composeWithDevTools() : Chrome devtools에서 확인할 수 있음.
const store = configureStore({ reducer: reducer }, composeWithDevTools());
import {useSelector,useDispatch} from 'react-redux';
const number = useSelector(state=>state.number);
const dispatch = useDispatch();
<button onClick={()=>{dispatch({type:'INCREASE'})}}>1증가</button>
<button onClick={()=>{dispatch({type:'DECREASE'})}}>1감소</button>
ex)
// store/counter.js
export const increase = () => ({type:'counter/INCREASE'});
export const decrease = () => ({type:'counter/DECREASE'});
const initialState = {
number:0
}
//reducer
function counter(state = initialState, action) {
swtich(action.type){
case 'counter/INCREASE' {
number: state.number + 1
}
case 'counter/DECREASE'{
number: state.number - 1
}
default:
returm state;
}
}
export default counter;
// store/index.js
import {combineReducers} from 'redux';
const rootReducer = combineReducers({
counter});
export default rootReducer;
음... 피드백환영