React 18悬念回退不工作的数据提取?



我基本上是获取一堆用户数据,并在页面加载时显示他们的用户名列表。我使用悬疑的目的是显示"Loading…"在处理userList组件时显示文本,但由于某些原因,它没有显示回退中提到的加载文本。我用的是最新的react 18版本。

import React, { useState, useEffect, Suspense } from "react";
function UsersList() {
// Fetches and returns List of users
const [users, setUsers] = useState([]);
useEffect(() => {
try {
fetch("https://jsonplaceholder.typicode.com/users")
.then((response) => response.json())
.then((data) => setUsers(data));
} catch (error) {
// handle the error here
}
}, []);
return (
<div>
<ul>
{users.map((user) => (
<li key={user.id}>{user.name}</li>
))}
</ul>
</div>
);
}
function App() {
return (
<div className="App">
<h2>Users List</h2>
<Suspense fallback={<h1> Loading...</h1>}>
<h4> Below are the user detailed fetched : </h4>
<UsersList />
</Suspense>
</div>
);
}
export default App;

我尝试使用节流来降低chrome开发工具的网络速度,但仍然没有显示加载文本。

您可以按如下方式更改代码:

import React,{useMemo,useState,Suspense} from 'react';
const wrapResponse = (promise) => {
let status = 'pending';
let data = '';
let error = '';
promise
.then(r => r.json())
.then(r => {
status = 'success';
data = r;
}).catch(e => {
status = 'error';
error = e;
})
return {
read(){
if(status === 'pending')
throw promise;
else if(status === 'success')
return data;
else if(status === 'error')
throw error;
}
}
}
function UsersList({resource}) {
// Fetches and returns List of users
// If fetch is pending , throw the promise and React will try to first 
// render UserList again with fallback UI: Loading...
const result = resource?.read();
const [users, setUsers] = useState(result);
return (
<div>
<ul>
{users.map((user) => (
<li key={user.id}>{user.name}</li>
))}
</ul>
</div>
);

function App() {
const resource = useMemo(() => 
wrapResponse(fetch("https://jsonplaceholder.typicode.com/users")),[]);
return (
<div className="App">
<h2>Users List</h2>
<Suspense fallback={<h1> Loading...</h1>}>
<h4> Below are the user detailed fetched : </h4>
<UsersList resource={resource}/>
</Suspense>
</div>
);
}
}

只要用悬念组件包装可能抛出Promise的组件,如果数据准备好了,状态将从'pending'变为'success', UI将从'Loading…’到你的UserList组件。

Suspense应该如何知道您正在获取数据?

From the docs:

只有启用了悬念的数据源才会激活悬念组件.
它们包括:

  • 使用启用悬浮的框架(如Relay和Next.js)获取数据
  • 使用lazy加载组件代码

悬念不检测数据何时在Effect或事件处理程序中获取。

暂置数据获取不支持使用自以为是的框架。实现启用suspend的数据源的需求是不稳定的,并且没有文档记录。用于将数据源与悬念集成的官方API将在React的未来版本中发布。

你还不能轻易地自己使用它。

最新更新