2017-12-27 349 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

相关问题