react-redux 의 connect 용법 소개 및 원리 분석
 
 흐름 도
connect 용법 소개
connect 방법 설명:
connect([mapStateToProps], [mapDispatchToProps], [mergeProps],[options])매개 변수 설명:
mapStateToProps(state, ownProps) : stateProps
const mapStateToProps = (state) => {
 return {
  count: state.count
 }
}(2)함수 의 두 번 째 매개 변수 인 ownProps 는 구성 요소 자체 의 props 입 니 다.어떤 때 는 ownprops 도 그 에 영향 을 미친다.
state 가 변 하거나 ownprops 가 변 할 때 mapStateToProps 가 호출 되 어 새로운 stateProps 를 계산 합 니 다.(ownprops merge 와 함께)구성 요소 에 업 데 이 트 됩 니 다.
mapDispatchToProps(dispatch, ownProps): dispatchProps
[mergeProps],[options][options](Object)이 인 자 를 지정 하면 connector 의 행동 을 맞 출 수 있 습 니 다.보통 안 써 요.
원리 해석
우선 connect 가 성공 한 이 유 는 Provider 구성 요소 때 문 입 니 다.
그럼 connect 는 뭐 했 어 요?
이것 은 진정 으로 Redux 와 React 를 연결 합 니 다.이것 은 우리 의 용기 구성 요소 의 바깥쪽 에 포함 되 어 있 습 니 다.이것 은 위의 Provider 가 제공 하 는 store 안의 state 와 dispatch 를 받 아 구조 함수 에 전달 하고 대상 을 되 돌려 주 며 속성 으로 우리 에 게 전달 하 는 용기 구성 요 소 를 받 습 니 다.
그것 의 소스 코드 에 대하 여
connect 는 고급 함수 입 니 다.먼저 mapStateToProps,mapDispatchToProps 를 전송 한 다음 에 Component 를 생산 하 는 함수(wrap Withconnect)를 되 돌려 준 다음 에 진정한 Component 를 매개 변수 로 wrap Withconnect 에 전달 하면 소 포 를 거 친 Connect 구성 요 소 를 생산 합 니 다.이 구성 요 소 는 다음 과 같은 특징 을 가지 고 있 습 니 다.
export default function connect(mapStateToProps, mapDispatchToProps, mergeProps, options = {}) {
 return function wrapWithConnect(WrappedComponent) {
  class Connect extends Component {
   constructor(props, context) {
    //    Component   store
    this.store = props.store || context.store
    this.stateProps = computeStateProps(this.store, props)
    this.dispatchProps = computeDispatchProps(this.store, props)
    this.state = { storeState: null }
    //  stateProps、dispatchProps、parentProps    
    this.updateState()
   }
   shouldComponentUpdate(nextProps, nextState) {
    //     ,        ,Component    
    if (propsChanged || mapStateProducedChange || dispatchPropsChanged) {
     this.updateState(nextProps)
      return true
     }
    }
    componentDidMount() {
     //   Component state
     this.store.subscribe(() = {
      this.setState({
       storeState: this.store.getState()
      })
     })
    }
    render() {
     //       Connect
     return (
      <WrappedComponent {...this.nextState} />
     )
    }
   }
   Connect.contextTypes = {
    store: storeShape
   }
   return Connect;
  }
 }
여기 서 우 리 는 카운터 사용 에 관 한 인 스 턴 스 를 씁 니 다.
Component/Counter.js
import React, {Component} from 'react'
class Counter extends Component {
  render() {
    //    props              
    const {increment, decrement, counter} = this.props;
    //    ,      ,    
    return (
      <p>
        Clicked: {counter} times
        {' '}
        <button onClick={increment}>+</button>
        {' '}
        <button onClick={decrement}>-</button>
        {' '}
      </p>
    )
  }
}
export default Counter;
import { connect } from 'react-redux'
import Counter from '../components/Counter'
import actions from '../actions/counter';
// state.counter   props counter
const mapStateToProps = (state) => {
  return {
    counter: state.counter
  }
};
// action        props 
const mapDispatchToProps = (dispatch, ownProps) => {
  return {
    increment: (...args) => dispatch(actions.increment(...args)),
    decrement: (...args) => dispatch(actions.decrement(...args))
  }
};
//  react-redux   connect        state     actions       props 
export default connect(mapStateToProps, mapDispatchToProps)(Counter)
Github: https://github.com/lipeishang/react-redux-connect-demo
이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
nginx 에서 사이트 아이콘 표시 설정전단 개발 환경: react:^16.4.1 webpack:^4.16.0 웹 팩 에 favicon. ico 설정 추가: nginx 는 ico 에 대한 지원 을 추가 합 니 다:...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.