数据库没有数据时,有一个页面显示No user。当数据库中有数据时,显示真实数据。代码如下
const [users, setUsers] = useState([]);
const [isLoading, setIsLoading] = useState(false)
useEffect(() => {
const fetchData = async () => {
try {
setIsLoading(true);
const response = await fetch(`/users`, {
method: 'GET',
headers: {
Authorization: `Bearer ${token}`,
}
});
if (response.ok) {
const data = await response.json();
if (data.success) {
setUsers(data.users);
}
} else {
console.log('Other HTTP Error:', response.status);
}
} catch (error) {
console.error('Error fetching users:', error);
} finally {
setIsLoading(false);
}
};
fetchData();
}, [token]);
const userList = () => {
if (isLoading) {
return <div>Loading...</div>;
}
const activedUsers = users
.filter((user) => user.status === 1);
if (activedUsers.length === 0) {
return(
<>
{activedUsers.length === 0 &&
<div>No user</div>
}
</>
)
}
return (
<>
{activedUsers.map((user) => (
<div key={user.userID}>
<Link to={`/user/${user.userID}`}>{user.Name}</Link>
</div>
))}
</>
)
}
我现在遇到的情况,第一次进入页面时,‘No user’总是会快速闪烁,然后会出现Loading,然后就会出现真实的数据。每次刷新页面都会出现这个问题。
正确的情况应该是先显示loading,然后有用户则显示用户,无用户则显示无用户。
有什么想法吗?
为了首先加载,您在定义它时设置了
isLoading
true
。
示例:
const [isLoading, setIsLoading] = useState(true)