setState是异步的,这就是为什么您将 books 视为空数组的原因。以下是React 文档中的引用:
setState函数用于更新状态。它接受新的状态值并将组件的重新渲染排入队列。
您可能做错的一件事是在您的useEffect回调中。如果你的效果返回一个函数,React 将在需要清理时运行它。并且您不希望在清理期间调用setState中的函数,因为组件可能会被卸载。fetchData
如果您只想fetchData在组件安装后运行一次,这里是一个可能的解决方案:
useEffect(() => {
// put the fetchData inside the effect
async function fetchData() {
setLoading(true);
const name = await getNameGroup();
const tmp = await getAll(name);
console.log(tmp);
setBooks(tmp);
console.log(books); // may not be the same as tmp, but you will see the updated state in the next render
setLoading(false);
}
fetchData();
},[]}
Run Code Online (Sandbox Code Playgroud)
您应该在React 文档中阅读有关useEffecthook的更多信息。
| 归档时间: |
|
| 查看次数: |
11481 次 |
| 最近记录: |