-
[redux] 리덕스 라이브러리 - 스토어 간편하게 사용하기React/redux 2023. 3. 17. 15:15
리덕스 라이브러리란?
1. 상태를 체계적으로 관리할 수 있다.
>> 프로젝트 규모가 클 때 적합하다.
2. 개발자 도구 지원해준다.
3. 미들웨어를 지원해준다.
>> 비동기 작업이 용이하다.
react-redux 사용하기
방법 1. 임시함수를 생성한다.
import React from 'react'; import Counter from '../components/Counter'; import { connect } from 'react-redux'; import { increase, decrease } from '../modules/counter'; const CounterContainer = ({number,increase,decrease}) => { return ( <div> <Counter number={number} onIncrease ={increase} onDecrease={decrease} /> </div> ); }; const mapStateToProps = state => ({ number : state.counter.number }) const mapDispatchToProps = dispatch => ({ increase : () => { dispatch(increase()) }, decrease : () => { dispatch(decrease()) } }); export default connect ( mapStateToProps, mapDispatchToProps, )(CounterContainer);
mapStateToProps,mapDispatchToProps 생성함!방법 2. connect 함수 안에서 미리 내장함수 선언한다.
import React from 'react'; import Counter from '../components/Counter'; import { connect } from 'react-redux'; import { increase, decrease } from '../modules/counter'; const CounterContainer = ({number,increase,decrease}) => { return ( <div> <Counter number={number} onIncrease ={increase} onDecrease={decrease} /> </div> ); }; export default connect ( state => ({ number : state.counter.number, }), dispatch => ({ increase : () => { dispatch(increase()) }, decrease : () => { dispatch(decrease()) } }), )(CounterContainer);
const mapDispatchToProps = dispatch => ({increase : () => {dispatch(increase())},decrease : () => {dispatch(decrease())}});방법 3. bindActionCreators 유틸 함수 사용
import React from 'react'; import { bindActionCreators } from 'redux'; import Counter from '../components/Counter'; import { connect } from 'react-redux'; import { increase, decrease } from '../modules/counter'; const CounterContainer = ({number,increase,decrease}) => { return ( <div> <Counter number={number} onIncrease ={increase} onDecrease={decrease} /> </div> ); }; export default connect ( state => ({ number : state.counter.number }), dispatch => bindActionCreators( {increase,decrease}, dispatch, ) )(CounterContainer);
export default connect (state => ({number : state.counter.number}),dispatch =>bindActionCreators({increase,decrease},dispatch,))(CounterContainer);방법 4. 액션 생성 함수로 이루어진 객체 형태로 넣기
두 번째 파라미터를 아예 객체 형태로 넣어 주면
connect 함수가 내부적으로 bindActionCreators 작업을 대신한다.
import React from 'react'; import Counter from '../components/Counter'; import { connect } from 'react-redux'; import { increase, decrease } from '../modules/counter'; const CounterContainer = ({number,increase,decrease}) => { return ( <div> <Counter number={number} onIncrease ={increase} onDecrease={decrease} /> </div> ); }; export default connect ( state => ({ number : state.counter.number }), { increase, decrease, } )(CounterContainer);
redux devTools로 state 확인
export default connect (state => ({number : state.counter.number}),{increase,decrease, })(CounterContainer);