2015-07-29 18 views
32

Uso le classi ES6 con Babel. Ho un componente React che assomiglia a questo:Perché getInitialState non viene chiamato per la mia classe React?

import { Component } from 'react'; 

export default class MyReactComponent extends Component { 
    getInitialState() { 
    return { 
     foo: true, 
     bar: 'no' 
    }; 
    } 

    render() { 
    return (
     <div className="theFoo"> 
     <span>{this.state.bar}</span> 
     </div> 
    ); 
    } 
} 

Non sembra come getInitialState viene chiamato, perché sto ottenendo questo errore: Cannot read property 'bar' of null.

risposta

59

Gli sviluppatori parlano del supporto di classe ES6 nel Release Notes for v0.13.0. Se si utilizza una classe ES6 che si estende React.Component, quindi si dovrebbe utilizzare un constructor() invece di getInitialState:

The API is mostly what you would expect, with the exception of getInitialState. We figured that the idiomatic way to specify class state is to just use a simple instance property. Likewise getDefaultProps and propTypes are really just properties on the constructor.

+0

Mi ci sono voluti alcuni minuti per capirlo, quindi ho voluto condividere questo come un Q & A poiché non ho trovato nulla su Google. – ndbroadbent

+0

Sì, getInitialState è solo una qualsiasi funzione generica a questo punto –

29

Codice per accompagnare Nathans risposta:

import { Component } from 'react'; 

export default class MyReactComponent extends Component { 
    constructor(props) { 
    super(props); 
    this.state = { 
     foo: true, 
     bar: 'no' 
    }; 
    } 

    render() { 
    return (
     <div className="theFoo"> 
     <span>{this.state.bar}</span> 
     </div> 
    ); 
    } 
} 
2

Per espandere un po 'su ciò che significa

getDefaultProps and propTypes are really just properties on the constructor.

il bit "on the constructor" è un testo strano. Nel normale linguaggio OOP significa solo che sono "variabili di classe statiche"

class MyClass extends React.Component { 
    static defaultProps = { yada: "yada" } 
    ... 
} 

o

MyClass.defaultProps = { yada: "yada" } 

si può anche fare riferimento a loro all'interno della classe come:

constructor(props) { 
    this.state = MyClass.defaultProps; 
} 

o con qualsiasi cosa dichiari come una variabile di classe statica. Non so perché non si parli di ovunque online per quanto riguarda le classi ES6:?

see the docs.

Problemi correlati