2017-12-27 330 views
0

我有以下反應本地程序:即使在我調用setState之後組件還會重新渲染?

class offerDetail extends Component { 
    constructor(props) { 
    super(props); 
    this.state = { 
     phone: null, 
     logo: null, 
     instagram: null 
    }; 
    const { name } = this.props.doc.data(); 
    this.ref = firebase.firestore().collection('companies').doc(name); 
    } 
    componentWillMount() { 
    let docObject = null; 
    this.ref.get().then(doc => { 
     let docObject = doc.data(); 
     console.log(docObject); -----------------------------1 
     }); 
     this.setState(
     docObject 

    ); 
     console.log(this.state); --------------------------------2 
    } 

    render() { 
    console.log(this.state);--------------------3 
... 

......

我有3個實例,其中我打印到控制檯。只有在實例編號1中它打印非空值,但是,在實例2和3中它打印空值。爲什麼實例2在setState之後立即調用時打印出null?

它是不是正確設置狀態,爲什麼?

回答

1

setState()在React中是異步的。

從陣營docs(第3款):

的setState()不總是立即更新組件。它可能會批處理或推遲更新,直到稍後。這使得在調用setState()之後立即讀取this.state是一個潛在的缺陷。相反,使用componentDidUpdate或回調的setState ...

如果你想一旦被更新爲訪問狀態,您可以添加一個回調,像這樣:

this.setState({ docObject },() => { 
    console.log(this.state.docObject); 
}); 
+0

,如果我想獲得什麼它從渲染方法裏面?正如你看到它在位置3處返回null。那是我真正需要它的地方嗎? –

+0

你將不得不執行一些檢查,「if(this.state.docObject){// loaded} else {// still null}'。 – Dan

相關問題