[React] React-Redux 정리

mapStateToProps

function mapStateToProps(state) {
  return {
    a: 42,
    todos: state.todos,
    filter: state.visibilityFilter
  }
}

// component will receive: props.a, props.todos, and props.filter
위처럼 작성하면 props.a / props.todos / props.filter를 통해 접근할 수 있다.


1. mapStateToProps는 단순히 store에서 state를 가져다 주는 것이 아니라 component가 바로 사용가능하도록 만들어야된다.
2. selector function을 사용할 것
3. mapStateToProps는 store에 변경사항이 있을때마다 호출되기때문에 최대한 빨라야한다.
4. mapStateToProps는 pure하고 synchronous해야된다.



mapDispatchToProps

const mapDispatchToProps = dispatch => {
  return {
    // dispatching plain actions
    increment: () => dispatch({ type: 'INCREMENT' }),
    decrement: () => dispatch({ type: 'DECREMENT' }),
    reset: () => dispatch({ type: 'RESET' })
  }
}
mapDispatchToProps를 사용하면 위에서 언급한 mapStateToProps처럼 props.increment()이런식으로 호출이 가능해진다.
React-Redux를 사용하면 store를 직접 접근하는일은 없다.
connect(mapStateToProps, mapDispatchToProps)(component)를 통해서 접근한다.

connect()는 인자로 넘긴 component를 싸고 있는 wrapper component를 반환한다. 이 wrapper component는 mapStateToProps와 mapDispatchToProps에서 전달한 Dispatcher와 state를 props로 포함시킨다.









댓글

이 블로그의 인기 게시물

[Django 공식문서 번역] REST Framework - Viewset and Router

[Django REST Framework] create() vs perform_create()

Intel Open WebRTC Toolkit(OWT) Media server 설치하는법