我的钩子没有返回我想要它获取的数据

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

我正在创建一个钩子来从数据库中获取所有属性。该函数是异步的,当我在另一个函数中调用钩子时,它是[]。我知道从数据库中获取的函数是异步的,我知道它必须等待服务器响应。我没有完全理解它,我如何获得返回我需要的数据的钩子?

我在另一个函数中使用了相同的逻辑来获取属性并且它起作用了,但是,我想把它放在一个钩子中,因为我将在程序的许多其他部分使用它。请不要对回答刻薄和居高临下,我正在学习这就是我来这里问的原因。

const getAllProperties = async () => {
const propertyRef = ref(database, "properties");

const getProperties = async () => (await get(propertyRef)).val();
const [allProperties, setAllProperties] = useState([]);

getProperties().then((properties) => {
  setAllProperties(properties ? Object.values(properties) : []);
});
console.log(allProperties);

return allProperties;
};
javascript reactjs asynchronous hook
1个回答
-1
投票

你的逻辑在两个方面是不正确的

  • 在 .then 之后访问变量将无法访问,而是使用 await 因为 .then 之后的代码将在调用函数后立即运行
  • 状态变量不会在设置后立即更新
setCount(1)
console.log(count) // will print pervious value
const getAllProperties = async () => {
const propertyRef = ref(database, "properties");

const getProperties = async () => (await get(propertyRef)).val();
const [allProperties, setAllProperties] = useState([]);

const properties = await getProperties()

setAllProperties(properties ? Object.values(properties) : []);

console.log(properties);

return properties;
};
© www.soinside.com 2019 - 2024. All rights reserved.