useEffect在React中返回不同的值



我有一个API要求在PostgreSQL查询,所以我有这个:

const getPresupuestos = () => {
return new Promise(function(resolve, reject) {
pool.query('SELECT * FROM presupuestos ORDER BY id ASC;', (error, results) => {
if (error) {
reject(error)
}
resolve(results.rows);
})
}) 
}

然后在索引中加上这个:

app.get('/', (req, res) => {
bd.getPresupuestos()
.then(response => {
res.status(200).send(response);
})
.catch(error => {
res.status(500).send(error);
})
})

问题是,我有一个反应应用程序,从那里我试图得到查询的值与此代码字符串:

const [presupuestos, setPresupuestos] = useState(false);
useEffect(() => {
getPresupuestos();
console.log(presupuestos) //return in console
}, []);
function getPresupuestos() {
fetch('http://localhost:3001')
.then(response => {
return response.text();
})
.then(data => {
setPresupuestos(data); //value wanted
});
}

我第一次执行这个,console.log返回我想要的查询,但是如果我刷新页面,我从相同的console.log得到一个false

我对React很陌生,所以如果有人能告诉我为什么会发生这种情况以及如何获得我需要的价值,我会很感激。

由于您的函数getPresupuestos在解决承诺后更新状态,这可能需要一些时间,并且您将无法在它之后获得其值。你能做的就是在promise的then中记录数据,即当它被解析时。

最新更新