What is the difference between using constructor vs getInitialState in React / React Native?

后端 未结 6 875
慢半拍i
慢半拍i 2020-11-28 17:24

I\'ve seen both used interchangeably.

What are the main use cases for both? Are there advantages / disadvantages? Is one a better practice?

6条回答
  •  没有蜡笔的小新
    2020-11-28 17:56

    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(
                   
                        
                        
                            Loading Data...
                        
                   
              );
         }
    
         renderLoadedView(){
              return(
                   
    
                   
              );
         }
    
         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({
    
    });
    

提交回复
热议问题