即使在我调用setState之后,组件也会重新渲染?

问题描述 投票:0回答:1

我有以下反应原生程序:

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中它会打印空值。如果在setState之后调用实例2,为什么实例2打印为null?

是不是它没有正确设置状态,为什么?

reactjs firebase react-native google-cloud-firestore
1个回答
1
投票

React中的setState()是异步的。

来自React docs(第3段):

setState()并不总是立即更新组件。它可以批量推迟更新或推迟更新。这使得在调用setState()之后立即读取this.state是一个潜在的陷阱。相反,使用componentDidUpdate或setState回调...

如果要在更新后访问该状态,可以添加如下所示的回调:

this.setState({ docObject }, () => {
  console.log(this.state.docObject);
});
© www.soinside.com 2019 - 2024. All rights reserved.