2017-09-29 3 views

Répondre

0

Nous devrions commencer par noter que les demandes externes doivent être manipulés avec soin dans React si la réactivité réelle fonctionne bien maintenir ses performances. C'est pourquoi nous allons créer une classe pour organiser cette logique de manière organisée.

const URL = 'https://api.coinmarketcap.com/v1/ticker/convert=EUR&limit=10'; 

// Our component now is a full class 
class BitcoinDisplay extends React.Component { 

    constructor(props) { 
    super(props); 

    // Start with no response available 
    this.state = {response: false}; 
    } 

    // Waits the component to be rendered before calling API 
    componentDidMount() { 
    axios.get(URL).then(response => { 
     // Updates the state with the response 
     this.setState({ response }) 
    }); 
    } 

    // Renders the component with the available data 
    render() { 
    if(!this.state.response) { 
     // Show a loading state because data may not be available yet 
     return 'Loading data...'; 
    } else { 
     return (<h1>{response.data[0].price_usd}</h1>); 
    } 
    } 
} 


Ensuite, vous le rendre dans les DOM.

ReactDOM.render(BitcoinDisplay, document.getElementById('app'));