我正在尝试为我的一门课程中的 React 作业创建自定义数据获取挂钩。是一个简单的钩子,它访问几个 REST API 端点并创建一个清单对象,应用程序将其用于组成沙拉的组件。问题是我似乎无法从useEffect
获取数据的钩子内设置钩子的内部状态。我以前多次使用过这种方法,我真的不知道是什么导致了这种行为。无论我setContent
在哪里尝试在我的useEffect
函数中使用它,它始终保持null
.
请帮忙!
const useInventory = (baseURL) => {
const [loading, setLoading] = useState(false);
const [content, setContent] = useState(null);
const [error, setError] = useState(null);
useEffect(() => {
setLoading(true);
const types = ['foundations', 'extras', 'proteins', 'dressings'];
const urls = types.map(endp => `${baseURL}/${endp}`);
Promise
.all(urls.map(u => fetch(u)))
.then(responses => Promise.all(responses.map(res => res.json())))
.then(data => {
const inventory = data.reduce((acc, curr, i) =>
({ ...acc, [types[i]]: curr }),
{});
// This logs the inventory in desired format
// e.g { foundations: Array, extras: Array, ... }
console.log(inventory);
setContent(inventory);
})
.catch(err => {
setError(err);
})
.finally(() => {
setLoading(false);
// This logs null, for some reason
console.log(content);
});
}, [baseURL]);
return [content, loading, error];
}
设置状态不是同步的,您不会在 finally 块中获得更新的内容。
如果您想调试内容更改的值,您可以使用 useEffect 和控制台,如下所示。
useEffect(() => {
console.log(content);
}, [content])
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句