在表中映射数据后得到空数组数据



基本上,我试图从axios获取数据然后将数据映射到material ui表中,但唯一的问题是在控制台上我的map未定义,我得到空数组

export default function BasicTable() {
const classes = useStyles();
const [form, setForm] = useState([]);
useEffect(() => {
axios
.get("http://localhost:8080/getForm")
.then((res) => setForm(res.data.form));

}, []);

return (
<TableContainer component={Paper}>
<Table className={classes.table} aria-label="simple table">
<TableHead>
<TableRow>
<TableCell> Bil</TableCell>
<TableCell align="right">Sales Dist.</TableCell>
<TableCell align="right">Sales Office&nbsp;(g)</TableCell>

</TableRow>
</TableHead>
<TableBody>
{form.map((p, index) => {
return (
<TableRow key={index}>
<StyledTableCell align="right">{p.sale}</StyledTableCell>
<StyledTableCell align="right">{p.district}</StyledTableCell>
<StyledTableCell align="right">{p.billing}</StyledTableCell>

</TableRow>
);
})}
</TableBody>
</Table>
</TableContainer>
);
}

使用async和await,它的工作很好,通常当我们调用get request时,我们应该处理await以获取所有数据,这是我调用get request的代码。

const API = "http://localhost:8080/getForm";
useEffect(() => {
const fetchData = async () => {
const result = await axios(API);
setForm(result.data);
};
fetchData();
}, []);

最新更新