your programing

React / React Native에서 생성자와 getInitialState를 사용하는 것의 차이점은 무엇입니까?

lovepro 2020. 10. 3. 11:26
반응형

React / React Native에서 생성자와 getInitialState를 사용하는 것의 차이점은 무엇입니까?


나는 둘 다 같은 의미로 사용되는 것을 보았다.

둘 다의 주요 사용 사례는 무엇입니까? 장단점이 있습니까? 하나가 더 나은 방법입니까?


두 가지 접근 방식은 서로 바꿔서 사용할 수 없습니다. 당신은 ES6 클래스를 사용할 때 생성자에서 상태를 초기화하고 정의해야합니다 getInitialState사용하는 경우 방법 React.createClass.

ES6 클래스 주제에 대한 공식 React 문서를 참조하십시오 .

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = { /* initial state */ };
  }
}

다음과 같다

var MyComponent = React.createClass({
  getInitialState() {
    return { /* initial state */ };
  },
});

차이 constructorgetInitialState의 차이점은 ES6ES5 자체.
getInitialState와 함께 사용되며 React.createClass함께
constructor사용됩니다 React.Component.

따라서 질문은 ES6 또는 ES5 사용의 장점 / 단점으로 귀결됩니다 .

코드의 차이점을 살펴 보겠습니다.

ES5

var TodoApp = React.createClass({ 
  propTypes: {
    title: PropTypes.string.isRequired
  },
  getInitialState () { 
    return {
      items: []
    }; 
  }
});

ES6

class TodoApp extends React.Component {
  constructor () {
    super()
    this.state = {
      items: []
    }
  }
};

이것에 관한 흥미로운 레딧 스레드 가 있습니다.

React 커뮤니티는 ES6에 가까워지고 있습니다. 또한 모범 사례로 간주됩니다.

React.createClass사이에는 약간의 차이가 React.Component있습니다. 예를 들어, this이러한 경우 어떻게 처리됩니다. 이 블로그 게시물자동 바인딩에 대한 페이스 북의 내용에서 이러한 차이점 대해 자세히 알아보십시오.

constructor이러한 상황을 처리하는데도 사용할 수 있습니다. 메서드를 구성 요소 인스턴스에 바인딩하려면 constructor. 이것은 멋진 일을하기에 좋은 재료입니다.


모범 사례에 대한 더 좋은 자료 React.js의 컴포넌트 상태 모범 사례
ES5에서 ES6로 React 프로젝트 변환

업데이트 : 2019 년 4 월 9 일 :

Javascript 클래스 API의 새로운 변경으로 인해 생성자가 필요하지 않습니다.

당신은 할 수 있습니다

class TodoApp extends React.Component {

    this.state = {items: []}
};

여전히 생성자 형식으로 변환되지만 걱정할 필요가 없습니다. 더 읽기 쉬운이 형식을 사용할 수 있습니다.

react hooks image React Hooks 사용

React 버전 16.8에는 새로운 API 호출 후크가 있습니다.

이제 상태를 갖기 위해 클래스 구성 요소도 필요하지 않습니다. 기능적 구성 요소에서도 수행 할 수 있습니다.

import React, { useState } from 'react';

function TodoApp () {
  const items = useState([]);

초기 상태는 인수로 전달됩니다 useState.useState([])

공식 문서에서 반응 후크에 대해 자세히 알아보세요.


OK, the big difference is start from where they are coming from, so constructor is the constructor of your class in JavaScript, on the other side, getInitialState is part of the lifecycle of React.

constructor is where your class get initialised...

Constructor

The constructor method is a special method for creating and initializing an object created with a class. There can only be one special method with the name "constructor" in a class. A SyntaxError will be thrown if the class contains more than one occurrence of a constructor method.

A constructor can use the super keyword to call the constructor of a parent class.

In the React v16 document, they didn't mentioned any preference, but you need to getInitialState if you using createReactClass()...

Setting the Initial State

In ES6 classes, you can define the initial state by assigning this.state in the constructor:

class Counter extends React.Component {
  constructor(props) {
    super(props);
    this.state = {count: props.initialCount};
  }
  // ...
}

With createReactClass(), you have to provide a separate getInitialState method that returns the initial state:

var Counter = createReactClass({
  getInitialState: function() {
    return {count: this.props.initialCount};
  },
  // ...
});

Visit here for more information.

Also created the image below to show few lifecycles of React Compoenents:

React lifecycle


If you are writing React-Native class with ES6, following format will be followed. It includes life cycle methods of RN for the class making network calls.

import React, {Component} from 'react';
import {
     AppRegistry, StyleSheet, View, Text, Image
     ToastAndroid
} from 'react-native';
import * as Progress from 'react-native-progress';

export default class RNClass extends Component{
     constructor(props){
          super(props);

          this.state= {
               uri: this.props.uri,
               loading:false
          }
     }

     renderLoadingView(){
          return(
               <View style={{justifyContent:'center',alignItems:'center',flex:1}}>
                    <Progress.Circle size={30} indeterminate={true} />
                    <Text>
                        Loading Data...
                    </Text>
               </View>
          );
     }

     renderLoadedView(){
          return(
               <View>

               </View>
          );
     }

     fetchData(){
          fetch(this.state.uri)
               .then((response) => response.json())
               .then((result)=>{

               })
               .done();

               this.setState({
                         loading:true
               });
               this.renderLoadedView();
     }

     componentDidMount(){
          this.fetchData();
     }

     render(){
          if(!this.state.loading){
               return(
                    this.renderLoadingView()
               );
          }

          else{

               return(
                    this.renderLoadedView()
               );
          }
     }
}

var style = StyleSheet.create({

});

These days we don't have to call the constructor inside the component - we can directly call state={something:""}, otherwise previously first we have do declare constructor with super() to inherit every thing from React.Component class then inside constructor we initialize our state.

If using React.createClass then define initialize state with the getInitialState method.

참고URL : https://stackoverflow.com/questions/30668326/what-is-the-difference-between-using-constructor-vs-getinitialstate-in-react-r

반응형