2017-12-21 8 views
1

이 질문은 여러 번 답변 된 것으로 생각되지만 구체적인 사례를 찾을 수 없습니다.React/Redux 구성 요소가 상태 변경시 다시 렌더링되지 않음

https://codesandbox.io/s/jjy9l3003

그래서 기본적으로 나는 (이 높은 경우는 false) 화면 크기를 조정할 미만 500 픽셀을 경우 true로 상태 호출 "isSmall"로 변경 작업

를 트리거 앱 구성 요소가
class App extends React.Component { 
... 
resizeHandeler(e) { 
    const { window, dispatch } = this.props; 
    if (window.innerWidth < 500 && !this.state.isSmall) { 
     dispatch(isSmallAction(true)); 
     this.setState({ isSmall: true }); 
    } else if (window.innerWidth >= 500 && this.state.isSmall) { 
     dispatch(isSmallAction(false)); 
     console.log(isSmallAction(false)); 
     this.setState({ isSmall: false }) 
    } 
    }; 

    componentDidMount() { 
    const { window } = this.props; 
    window.addEventListener('resize', this.resizeHandeler.bind(this)); 
    } 
... 

저는 HeaderContainer라는 다른 구성 요소가 있는데, App의 하위이며 저장소와 상태 "isSmall"에 연결되어 있습니다.이 구성 요소가 "isSmall"변경 상태 일 때 다시 렌더링되기를 원하지만 ...

class Header extends React.Component { 

    constructor(props) { 
    super(props); 

    this.isSmall = props.isSmall; 
    this.isHome = props.isHome; 
    } 
    ... 
    render() { 
    return (
     <div> 
     { 
      this.isSmall 
      ? 
      (<div>Is small</div>) 
      : 
      (<div>is BIG</div>) 
     } 
     </div> 
    ); 
    } 
    ... 

비록 내가 콘솔을 통해 볼 수 있다면 redux가 실제로 저장소 요소를 업데이트하고 있습니다. 헤더 구성 요소가 다시 렌더링되지 않습니다. 누군가 내가 누락 된 부분을 지적 할 수 있습니까?

"connect()"redux-react 함수를 잘못 이해하고 있습니까?

답변

1

당신이 당신의 구성 요소는 당신이 당신의 mapStateToProps 기능에 액세스하는 소품 (ISHOME 및 isSmall가)에서 가져온 것을 의미 connect

const mapStateToProps = (state, ownProps) => { 
    return { 
    isHome: ownProps.isHome, 
    isSmall: state.get('isSmall') 
    } 
} 


export const HeaderContainer = connect(mapStateToProps)(Header); 

를 통해 REDUX 저장소에 연결되어 게시 된 링크 코드를 보면 redux 저장소 및 구성 요소로 소품으로 전달합니다.

사용 할 구성 요소를 재 렌더링 반응하게하려면 'this.props'(마다 소품의 변화라고 렌더링 같은) render 기능 내부 : 당신이 잘하고있는

render() { 
    return (
     <div> 
     { 
      this.props.isSmall 
      ? 
      (<div>Is small</div>) 
      : 
      (<div>is BIG</div>) 
     } 
     </div> 
    ); 
    } 

constructor이지만 구성 요소가 마운트되기 전에 생성자가 한 번만 호출됩니다. 반응 라이프 사이클 방법을 살펴 봐야합니다. https://reactjs.org/docs/react-component.html#constructor

Header.js 파일에서 전체적으로 constructor을 제거 할 수 있습니다.

는 또한 공공 클래스 속성 (예를 들어, this.isSmall = props.isSmall;)을 사용하지 않아야합니다

가능하면 반응을 활용 당신의 구성 요소가 필요로 할 때 로컬 상태 반응 : 지금 https://reactjs.org/docs/state-and-lifecycle.html#adding-local-state-to-a-class

+0

감사합니다, 그것은 만들 SENS를 – Sylou

1

구성 요소는 한 번만 마운트 된 후 새 소품을 전달하면 업데이트됩니다. 따라서 생성자는 마운트 전에 한 번만 호출됩니다. 즉, 거기에 설정 한 인스턴스 속성은 마운트 된 구성 요소의 수명 동안 절대로 변경되지 않습니다. 업데이트 작업을 위해 render() 함수에서 this.props에 직접 액세스해야합니다. 이 경우에는 아무 것도하지 않기 때문에 생성자를 제거 할 수 있습니다.