【发布时间】:2021-03-16 17:39:32
【问题描述】:
我正在构建一个 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 为空,则会显示一条消息,如没有课程。当数组已满时,数据以表格行呈现。
我的问题是:当courses 已满并呈现CoursesTable.js 时,没有课程消息总是出现几毫秒,然后被数据替换。 p>
我该如何解决这个问题?谢谢你们的帮助!
【问题讨论】:
标签: javascript reactjs api axios use-effect