IT

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

lottoking 2020. 6. 1. 08:10
반응형

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


React 에서이 두 구현 사이에 실제 차이점이 있습니까? 어떤 친구들은 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 = {} (감사합니다)로 변경했지만 여전히 차이가 보이지 않습니다. 하나가 다른 것보다 낫습니까?


상태로 변경되지 않는 속성을 복사하는 것은 안티 패턴입니다 (이 경우 .props에 직접 액세스). 결국 변경되지만 .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),
  };
}

This is a shorthand equivalent to the answer from @joews below. It seems to only work on more recent versions of es6 transpilers, I have had issues with it on some webpack setups. If this doesn't work for you, you can try adding the babel plugin babel-plugin-transform-class-properties, or you can use the non-shorthand version by @joews below.


You don't need to call setState in a Component's constructor - it's idiomatic to set this.state directly:

class FirstComponent extends React.Component {

  constructor(props) {
    super(props);

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

See React docs - Adding Local State to a Class.

There is no advantage to the first method you describe. It will result in a second update immediately before mounting the component for the first time.


Update for React 16.3 alpha introduced static getDerivedStateFromProps(nextProps, prevState) (docs) as a replacement for componentWillReceiveProps.

getDerivedStateFromProps is invoked after a component is instantiated as well as when it receives new props. It should return an object to update state, or null to indicate that the new props do not require any state updates.

Note that if a parent component causes your component to re-render, this method will be called even if props have not changed. You may want to compare new and previous values if you only want to handle changes.

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

It is static, therefore it does not have direct access to this (however it does have access to prevState, which could store things normally attached to this e.g. refs)

edited to reflect @nerfologist's correction in comments


You could use the short form like below if you want to add all props to state and retain the same names.

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

If you directly init state from props, it will shows warning in React 16.5 (5th September 2018)


you could use key value to reset state when need, pass props to state it's not a good practice , because you have uncontrolled and controlled component in one place. Data should be in one place handled read this https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html#recommendation-fully-uncontrolled-component-with-a-key


set the state data inside constructor like this

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

it will not going to work if u set in side componentDidMount() method through props.

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

반응형