使用React useEffect获取数据和条件渲染



我正在构建一个MERN堆栈应用程序,它可以获取有关大学课程的数据并将其呈现在表中。CoursesTable.js组件如下所示:

import React, { useState, useEffect  } from 'react';
import { Table } from 'react-materialize';
import axios from 'axios';
const CoursesTable = () => {
const [courses, setCourses] = useState([]);
useEffect(() => {
const fetchData = async () => {
const coursesData = await axios.get('http://localhost:8001/')
setCourses(coursesData.data)
}
fetchData()
}, [])
return (
<Table>
<thead>
<tr>
<th data-field="course-name">
Name
</th>
<th data-field="course-prof">
Prof.
</th>
<th data-field="course-code">
Code
</th>
</tr>
</thead>
<tbody>
{
courses.length >= 1
? courses.map(course => 
<tr key={course._id}>
<td>
{course.name}
</td>
<td>
{course.prof}
</td>
<td>
{course.code}
</td>
</tr>
)
: <tr>
<td>There is no course</td>
</tr>
}
</tbody>
</Table>
);
}
export default CoursesTable;

我使用条件呈现,这样,如果courses为空,就会显示一条类似There is no course的消息。当数组已满时,数据将呈现在表行中。

我的问题是:当courses已满并且CoursesTable.js已呈现时,There is no course消息总是在用数据替换之前出现几毫秒。

我该怎么解决这个问题?谢谢你们的帮助!

您可以进行条件检查,例如:

import React, { useState, useEffect  } from 'react';
import { Table } from 'react-materialize';
import axios from 'axios';
const CoursesTable = () => {
const [courses, setCourses] = useState([]);
const [isLoading, setLoading] = useState(true);
useEffect(() => {
const fetchData = async () => {
const coursesData = await axios.get('http://localhost:8001/')
setCourses(coursesData.data)
setLoading(false);
}
fetchData()
}, [])
if(isLoading) { return <div> Loading ... </div> };
return (
<Table>
<thead>
<tr>
<th data-field="course-name">
Name
</th>
<th data-field="course-prof">
Prof.
</th>
<th data-field="course-code">
Code
</th>
</tr>
</thead>
<tbody>
{
courses.length >= 1
? courses.map(course => 
<tr key={course._id}>
<td>
{course.name}
</td>
<td>
{course.prof}
</td>
<td>
{course.code}
</td>
</tr>
)
: <tr>
<td>There is no course</td>
</tr>
}
</tbody>
</Table>
);
}
export default CoursesTable;

最新更新