source

컨스트럭터 vs componentWillMount. componentWillMount는 컨스트럭터로는 할 수 없는 일을 componentWillMount는 어떻게 할 수 있습니까?

itover 2023. 3. 8. 21:07
반응형

컨스트럭터 vs componentWillMount. componentWillMount는 컨스트럭터로는 할 수 없는 일을 componentWillMount는 어떻게 할 수 있습니까?

내가 본 바로는, 유일한 것은componentWillMount할 수 있다constructor전화할 수 없다setState.

componentWillMount() {
    setState({ isLoaded: false });
}

전화 안 했으니까render근데...setStatecomponentWillMount첫 번째 입력 전에 상태 객체를 준비합니다.render()통과. 그건 본질적으로 같은 것이다.constructor다음 작업을 수행합니다.

constructor(props) {
    super(props);
    this.state = { isLoaded: false };
}

하지만 또 다른 사용 사례가 있습니다.componentWillMount는(서버측에서) 편리합니다.

비동기적인 것에 대해 생각해 봅시다.

componentWillMount() {
    myAsyncMethod(params, (result) => {
        this.setState({ data: result });
    })
}

여기서는constructor에의 할당으로서this.state트리거되지 않음render().

어때setStatecomponentWillMountReact 문서에 따르면:

componentWillMount()는 마운트 발생 직전에 호출됩니다.그것은 전에 불려진다.render(이 때문에, 이 메서드로 상태를 설정해도, 재검출은 트리거 되지 않습니다.이 방법에서는 부작용이나 구독이 발생하지 않도록 합니다.

이 경우 React는 첫 번째 렌더링에 새로운 상태 값을 사용하고 재렌더를 회피합니다.

질문 1: 즉, 내부가componentWillMount전화하면setState비동기 방식의 콜백(약속 콜백일 수 있음)에서 리액트는 콜백이 실행될 때까지 초기 렌더링을 차단합니까?

클라이언트측에서 이 셋업을 하고 있는 경우(서버측 렌더링에서의 유스케이스를 알 수 있습니다), 상기 내용이 참이라고 가정했을 경우, 비동기 방식이 완료될 때까지 아무것도 표시되지 않습니다.

제가 놓친 개념이 있나요?

질문 2: 다음 방법으로 달성할 수 있는 다른 사용 사례가 있습니까?componentWillMount이 명령어를 사용하지 않고constructor그리고.componentDidMount?

즉, componentWillMount 내부에서 비동기 메서드의 콜백(약속 콜백일 수 있음)으로 setState를 호출하면 React는 콜백이 실행될 때까지 초기 렌더링을 차단한다는 의미입니까?

아니, 여기 .

다음 코드는 렌더링을 차단하지 않습니다(setState를 호출하는 것은 어쨌든 안티 패턴임을 유의하십시오).

componentWillMount: function() {
     new Promise((resolve, reject) => {
        setTimeout(()=> {
            resolve();
        }, 2000)
     }).then(() => this.setState({ promiseResult: 'World' }));
  },

질문 2: componentWillMount에서만 달성할 수 있는 다른 사용 사례는 componentWillMount와 componentDidMount를 사용하지 않는 것입니까?

아니요, ES6 클래스의 경우 componentWillMount를 폐기할 수 있습니다.이 기능은 다음 명령어를 사용하는 경우에만 필요합니다.React.createClass({... })

편집: 분명히 제가 틀렸습니다.이것을 지적해 주신 @Swapnil님 감사합니다.여기 토론이 있습니다.

리액션은 에 부작용이 있을 경우 경고를 보냅니다.constructor다른 컴포넌트의 스테이트를 변경합니다.왜냐하면 이 컴포넌트는setState constructor 및 으로 '중' 동안render()을 사용하다.constructor요구되고 있습니다.

이, , 릅, 릅, 릅, 하면 .componentWillMount에러는 발생하지 않습니다.을 억제한다.componentWillMount 이 약을 될 것 같아요.constructorcomponentWillMountcomponentDidMountcomponentWillMount어느 쪽이든, 당신은 이 모든 것을componentWillMount.

언급URL : https://stackoverflow.com/questions/40828004/constructor-vs-componentwillmount-what-a-componentwillmount-can-do-that-a-const

반응형