我正在使用MongoDB
从axios
数据库中提取数据,并将其值设置为名为发票的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)
}
什么可能是问题的原因,我该如何解决?
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);
});
}
如果要在第一次加载页面时查看数据,请尝试服务器端呈现
componentDidUpdate
或render
功能中看到更新的内容。编辑:您还可以访问声明的更新,如下所示;
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);
});
}