为什么无法在componentDidMount中访问ReactJS状态

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

我正在使用MongoDBaxios数据库中提取数据,并将其值设置为名为发票state

我在componentDidMount中执行此操作。再一次,我想访问componentDidMount中的状态(即发票)。我试图将invoices值设置为另一个state值,称为dataa。但是总会变成空/空。

问题是尚未设置状态,值为空

这是我的代码段的样子:

componentDidMount() {

axios
  .get("http://localhost:4005/purchaseinvoices")
  .then(response => {
    this.setState({
      invoices: response.data //setting value to invoices
    });
  })
  .then(
    this.setState({
      dataa: this.state.invoices //setting value to dataa
    })
  )
  .catch(err => {
    console.log(err);
  });

  //but this gives 0
  alert(this.state.invoices.length)

}

什么可能是问题的原因,我该如何解决?

javascript reactjs
2个回答
0
投票
componentDidMount() { axios .get("http://localhost:4005/purchaseinvoices") .then(response => { this.setState({ invoices: response.data //setting value to invoices data: response.data }); }) .catch(err => { console.log(err); }); }

如果要在第一次加载页面时查看数据,请尝试服务器端呈现


0
投票
但是,您可以在componentDidUpdaterender功能中看到更新的内容。

编辑:您还可以访问声明的更新,如下所示;

axios .get("http://localhost:4005/purchaseinvoices") .then(response => { this.setState({ invoices: response.data, //setting value to invoices dataa: response.data }, () => { alert(this.state.invoices.length) }); }) .catch(err => { console.log(err); }); }

© www.soinside.com 2019 - 2024. All rights reserved.