2017-12-27 3 views
0

반응하는 ModalSwitch 클래스는는 반응 라우터 공식 <a href="https://reacttraining.com/react-router/web/example/modal-gallery" rel="nofollow noreferrer">example</a>에 라우터 속성 값

previousLocation = this.props.location 

가 왜 클래스 내에서 첫 번째 줄에 다음 코드

class ModalSwitch extends React.Component { 

    previousLocation = this.props.location 

    componentWillUpdate(nextProps) { 
     const {location} = this.props 
     if (
      nextProps.history.action !== 'POP' && 
      (!location.state || !location.state.modal) 
     ) { 
      this.previousLocation = this.props.location 
     } 
    } 

    render() { 
     const {location} = this.props 
     const isModal = !!(
      location.state && 
      location.state.modal && 
      this.previousLocation !== location 
     ) 
     return (
      // ... 
     ) 
    } 
} 
  1. 으로,이 previousLocation이 이런 방식으로 선언 되었습니까?

    previousLocation 전에 const을 추가해야한다고 생각했는데 구문 오류가 있기 때문에 잘못 되었습니까?

    const previousLocation = this.props.location // syntax error 
    

    이 아니면 내가 constructor 함수 내에서 previousLocation을 넣어해야한다고 생각하지만, 다시는

    constructor(){ 
        super(); 
        this.previousLocation = this.props.location // this.props would be undefined, why? 
    } 
    
  2. 이 두 번째 질문이 될 것이다 잘못 : 다음과 같은 장소에서 this.props 동일의 값은?

    1. 들어

답변

1

previousLocation 클래스의 재산이기 때문에

previousLocation = this.props.location 

componentWillUpdate(nextProps) {...} 

render(){...} 
, 그래서 const를 할 필요가 없습니다. 나는 그들이 transform-class-properties 플러그인을 사용하고 있다고 생각한다. here

ES transpiler는 클래스 생성자에 속성을 초기화하기 위해 코드를 변환합니다. 당신은 다음과 같이 할 필요가 있으므로

constructorprops 사전을 받게됩니다 : 2의 대답은 '예

constructor(props){ 
    super(props); 
    this.previousLocation = this.props.location // this.props would be assign by super(props), in your code, props is undefined. 
    this.previousLocation = props.location 
} 

입니다. 보다 정확함 : 모두 현재 구성 요소의 '소품'속성을 가리 킵니다. 생성자에서 원래의 소품은 부모 구성 요소에서 전달되었습니다. 'componentWillUpdate'에서 'props'는 업데이트 소품을 받기 전에 이전 소품이됩니다. render에서 렌더링 할 때 'props'가 있습니다. 콘솔 로그에서 this.props는 다른 값을 갖지만 의미는 같습니다.

것은 당신이 코드를 다음과 같습니다 :

예를 들어

<Component property={this.state.value} /> 

을 그리고 state.value 5. 그런 다음 constructor 호출 될 것이며, 다음 render입니다. 상태가 변경된 경우 this.props.value는 부모 구성 요소 5.

됩니다

setState({value: 6}). 

그럼 componentWillUpdate 호출한다. this.props.value은 오래된 소품이고 값은 5이며 newProps.value은 6이됩니다. 그러면 props이 업데이트되고 render이 호출됩니다. render에서 this.props.value는 6입니다.

+0

감사합니다. @ Daniel Tran, 정말 감사드립니다! 질문 1에 대한 귀하의 대답은 정확합니다. 당신의 질문 1의 대답과 함께, 나는 당신이했던 것과 console.log (이전 위치)와 그 값을 볼 수있는 코드를 수정할 수 있습니다.그러나 질문 2에 대한 귀하의 대답은 잘못된 것 같습니다. 다른 위치로 이동할 때 constructor(), componentWillUpdate() 및 render() 내부의 빠른 console.log (this.props)가 다른 값을 표시하는지, 내가 맞는지 확인하십시오. – webberpuma

+0

설명을위한 답변을 업데이트하십시오. –

+0

좋습니다. 이제 분명합니다. 나는 대답을 수락합니다. 그래도 문법이 더 나을 수 있습니다. – webberpuma