gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 03:30:07 25 4
gpt4 key购买 nike

我使用 axiosMongoDB 数据库中提取数据,并将值设置为名为 invoicesstate 值>

我在componentDidMount中执行此操作。我想再次访问 componentDidMount 中的状态(即发票)。我正在尝试将 invoices 值设置为另一个名为 dataastate 值。但最终总是会变得空/空。

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

这就是我的代码片段的样子:

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)

}

问题的可能原因是什么以及如何解决这个问题?

最佳答案

直接从响应更新数据,而不是使用 this.state.invoices。因为 this.setState 是一个异步调用,需要一些毫秒的延迟来更新状态。

 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);
});


}

如果您想在页面首次加载时查看数据,请尝试服务器端渲染

关于javascript - 为什么在 componentDidMount 中无法访问 ReactJS 状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58249699/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com