설치
yarn add redux
yarn add react-redux
1. 화면에 보일 UI만들기
2. 리듀서 만들기
3. 리듀서 합치기 : combineReducers
4. index.js에 스토어 생성해서 3번 리듀서 자식(자손)컴포넌트에 전달하기
5. 원하는 UI에 액션, state 연결해서 사용하기
1. UI 디자인
2. 리듀서만들기
//1. 액션 - 모듈이름을 앞에 붙여줌으로써 액션명 중복방지
const AAA = 'counter/AAA';
//4. 액션생성함수 후 내보내기
export const aaa = () => ({ type: AAA });
//dispatch({type: AAA}) -> dispatch( aaa() )
//dispatch({type: AAA , 값}) -> dispatch( aaa(값) )
//2. 초기 상태값
const initialState = { number: 0 };
//3. 순수 함수 - reducer 함수 만들기
const reducer = ( state = initialState, action ) => {
switch( action.type ){
case AAA :
return {
number: 0
}
default:
return state
}
}
export default reducer
3. 리듀서 합치기
import { combineReducers } from 'redux';
import 리듀서이름1 from './리듀서파일1';
import 리듀서이름2 from './리듀서파일2';
import 리듀서이름3 from './리듀서파일3';
export default combineReducers({
리듀서이름1,
리듀서이름2,
리듀서이름3
});
>> 4. index.js에 스토어 생성해서 3번 리듀서 자식(자손)컴포넌트에 전달하기
src/index.js
import rootReducer from './store'; 리듀서 파일 붙러오기
const store = createStore(rootReducer); 스토어데 리듀서 파일넣기
import { Provider } from 'react-redux';
const store = createStore( rootReducer ) 스토어생성
<Provider store={store}>
<App />
</Provider>
>> 5. components안에 UI에 액션, state 연결해서 사용하기
useDispatch : 액션처리
useSelector : 상태값 처리
import { useDispatch , useSelector } from 'react-redux'
//상태값가져오기
const state담을이름 = useSelector( state => state.리듀서파일명.state명 )
const dispatch = useDispatch()
<button onClick={() => dispatch( 리듀에서내보낸액션명() )}>변경</button>
import { composeWithDevTools } from 'redux-devtools-extension'; // 리덕스 개발자 도구
const store = createStore(rootReducer, composeWithDevTools());
// composeWithDevTools 를 사용하여 리덕스 개발자 도구 활성화
설치
yarn add redux-devtools-extension