React map()数据未显示
2022-04-22
1568
数据未出现在视图中的表中。已使用控制台确认从数据库导入数据。 在此处输入图像说明
如果仅将其用作 list.map(),则会出现错误,指出它不是函数。所以 list && list.length > 0 ?我正在使用 list.map((e)。 或者我必须修改 const [list, setList] = useState 代码部分?
import React, { useEffect, useState } from "react";
import axios from 'axios';
import Navbar from './Navbar';
import Box from '@mui/material/Box';
import Button from '@mui/material/Button';
import Table from '@mui/material/Table';
import TableBody from '@mui/material/TableBody';
import TableCell from '@mui/material/TableCell';
import TableContainer from '@mui/material/TableContainer';
import TableHead from '@mui/material/TableHead';
import TableRow from '@mui/material/TableRow';
import Paper from '@mui/material/Paper';
export default function Community() {
const [list, setList] = useState([{
inputData: {
post_id: '',
title: '',
writer: ''
},
}]);
useEffect(() => {
axios.get('http://localhost:5000/post/community').then((res) => {
console.log("성공");
console.log(res.data);
setList(res.data);
})
}, [])
return (
<div>
<Navbar />
<Box>
<Button sx={{ fontWeight: 'bold' }} href="/newpost">게시글 등록</Button>
</Box>
<TableContainer component={Paper}>
<Table aria-label="simple table">
<TableHead>
<TableRow>
<TableCell sx={{ fontWeight: 'bold' }}>Post_id</TableCell>
<TableCell sx={{ fontWeight: 'bold' }}>Title</TableCell>
<TableCell sx={{ fontWeight: 'bold' }} align="right">Writer</TableCell>
</TableRow>
</TableHead>
{list && list.length > 0 ? list.map((e) => {
return (
<TableBody>
<TableRow key={e.post_id}>
<TableCell component="th" scope="row">{e.post_id}</TableCell>
<TableCell align="right">{e.title}</TableCell>
<TableCell align="right">{e.writer}</TableCell>
</TableRow>
</TableBody>
)
}) : ""}
</Table>
</TableContainer>
</div>
);
}
1个回答
您的第一个状态设置错误,导致地图无法更新状态数据。它只会变异而不会更新。
将
const [list, setList] = useState([{
inputData: {
post_id: '',
title: '',
writer: ''
},
}]);
更改为
const [list, setList] = useState([])
Matt
2022-04-22