programing

소품에서 구성 요소 초기화 상태 반응

prostudy 2022. 3. 26. 16:44
반응형

소품에서 구성 요소 초기화 상태 반응

반응에서, 이 두 구현 간에 실제적인 차이가 있는가?몇몇 친구들은 나에게 말한다.FirstComponent패턴이지만 왜 그런지 모르겠어SecondComponent렌더가 한 번만 호출되기 때문에 더 간단해 보인다.

첫 번째:

import React, { PropTypes } from 'react'

class FirstComponent extends React.Component {

  state = {
    description: ''
  }

  componentDidMount() {
    const { description} = this.props;
    this.setState({ description });
  }

  render () {
    const {state: { description }} = this;    
    return (
      <input type="text" value={description} /> 
    );
  }
}

export default FirstComponent;

두 번째:

import React, { PropTypes } from 'react'

class SecondComponent extends React.Component {

  state = {
    description: ''
  }

  constructor (props) => {
    const { description } = props;
    this.state = {description};
  }

  render () {
    const {state: { description }} = this;    
    return (
      <input type="text" value={description} />   
    );
  }
}

export default SecondComponent;

업데이트: 변경됨setState()this.state = {}(고마워 조우즈) 하지만, 나는 여전히 차이를 보지 못한다.하나가 다른 것보다 나은가?

상태(그 경우 직접 .propes에 액세스하기만 함)로 결코 변경되지 않는 속성을 복사하는 것은 안티 패턴이라는 점에 유의해야 한다.결국 변경되지만 .props의 값으로 시작하는 상태 변수가 있는 경우 생성자 호출이 필요하지 않음 - 이러한 로컬 변수는 부모 생성자에 대한 호출 후 초기화됨:

class FirstComponent extends React.Component {
  state = {
    x: this.props.initialX,
    // You can even call functions and class methods:
    y: this.someMethod(this.props.initialY),
  };
}

이것은 아래 @joews의 대답에 해당하는 속기다.그것은 좀 더 최신 버전의 es6 트랜스필러에서만 작동하는 것 같아, 나는 몇몇 웹팩 설정에서 그것에 문제가 있었다.이 방법이 작동하지 않으면 babel 플러그인을 추가해 보십시오.babel-plugin-transform-class-properties또는 아래 @ws로 비속어 버전을 사용할 수 있다.

전화할 필요 없다.setState컴포넌트의constructor- 설정하는 것은 관용적이다.this.state직접:

class FirstComponent extends React.Component {

  constructor(props) {
    super(props);

    this.state = {
      x: props.initialX
    };
  }
  // ...
}

문서 대응 - 클래스에 로컬 상태 추가를 참조하십시오.

당신이 묘사한 첫 번째 방법에는 이점이 없다.구성 요소를 처음 장착하기 직전에 두 번째 업데이트가 발생한다.

React 16.3 알파에 대한 업데이트 소개static getDerivedStateFromProps(nextProps, prevState)(문서)를 대신하여componentWillReceiveProps.

getDeorivedStateFromProps는 구성요소가 인스턴스화된 후 그리고 새로운 소품을 받은 후에 호출된다.개체를 반환하여 상태를 업데이트하거나, 새 소품에는 상태 업데이트가 필요하지 않음을 나타내기 위해 null을 반환해야 한다.

상위 구성요소가 구성요소를 다시 렌더링하도록 하는 경우, 소품이 변경되지 않았더라도 이 메서드는 호출된다는 점에 유의하십시오.변경 사항만 처리하려면 새 값과 이전 값을 비교하십시오.

https://reactjs.org/docs/react-component.html#static-getderivedstatefromprops

정적이므로 에 직접 접근할 수 없다.this(하지만 에 대한 액세스 권한이 있다)prevState에 부착된 물건을 보관할 수 있는 것.this예)refs)

@nerfologist의 정정 사항을 코멘트에 반영하기 위해 편집된

만약 당신이 모든 소품들을 동일한 이름을 명시하고 유지하기를 원한다면 당신은 아래와 같은 짧은 양식을 사용할 수 있다.

constructor(props) {
    super(props);
    this.state = {
       ...props
    }
    //...
}

생성자에서 초기화할 때 주의해야 한다.라 할지라도props새로운 것으로 바뀌면 다시는 산이 일어나지 않기 때문에 주가 바뀌지 않을 것이다.그것을 위해 존재한다.

class FirstComponent extends React.Component {
    state = {
        description: ""
    };
    
    static getDerivedStateFromProps(nextProps, prevState) {
        if (prevState.description !== nextProps.description) {
          return { description: nextProps.description };
        }
    
        return null;
    }

    render() {
        const {state: {description}} = this;    

        return (
            <input type="text" value={description} /> 
        );
    }
}

또는 사용key초기화를 위한 트리거로 사용되는 소품:

class SecondComponent extends React.Component {
  state = {
    // initialize using props
  };
}
<SecondComponent key={something} ... />

위의 코드에서 다음과 같은 경우something그 다음, 바뀌었다.SecondComponent새로운 인스턴스로 다시 마운트되며state에 의해 초기화될 것이다.props.

시공자 내부의 상태 데이터를 이와 같이 설정한다.

constructor(props) {
    super(props);
    this.state = {
      productdatail: this.props.productdetailProps
    };
}

만약 네가 편을 들면 그것은 작동하지 않을 것이다.componentDidMount()소품을 통한 방법

소품에서 직접 상태를 초기화하면 반응 16.5(2018년 9월 5일)에 경고가 표시된다.

너는 할 수 있다key필요할 때 재설정하는 값, 소품을 전달하여 한 곳에 제어되지 않고 제어되지 않는 구성요소를 가지고 있기 때문에 좋은 관행이 아니라는 것을 진술하십시오.데이터는 한 곳에서 취급되어야 한다. 본 https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html#recommendation-fully-uncontrolled-component-with-a-key

componentWillReceiveProps를 사용할 수 있다.

constructor(props) {
    super(props);
    this.state = {
      productdatail: ''
    };
}

componentWillReceiveProps(nextProps){
    this.setState({ productdatail: nextProps.productdetailProps })
}

참조URL: https://stackoverflow.com/questions/40063468/react-component-initialize-state-from-props

반응형