Я хотел бы спросить вас, почему мой код React работает так странно. Класс компонента:
import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import Table from '@material-ui/core/Table';
import TableBody from '@material-ui/core/TableBody';
import TableCell from '@material-ui/core/TableCell';
import TableContainer from '@material-ui/core/TableContainer';
import TableHead from '@material-ui/core/TableHead';
import TableRow from '@material-ui/core/TableRow';
import Paper from '@material-ui/core/Paper';
class ReservationsTable extends React.Component {
constructor(props) {
super(props);
this.state = {
rows : []
};
}
async componentDidMount() {
const tData = [];
const userString = localStorage.getItem('user');
const user = JSON.parse(userString);
const reservationsProm = fetch('http://localhost:8000/api/reservations/', { method: 'get' }).then((res) => res.json());
const reservations = await reservationsProm;
const currentUserRes = reservations.filter((res) => res.client == user.id);
currentUserRes.forEach(async (res) => {
const url = `http://localhost:8000/api/books/${res.book}`;
const book = await fetch(url);
const bookData = await book.json();
const sDate = new Date(res.startDate).toDateString();
const tDate = new Date(res.returnDate).toDateString();
const displayObj = {
title: bookData.title,
from: sDate,
to: tDate
};
tData.push(displayObj);
})
this.setState({ rows: tData }, () => console.log(this.state.rows));
}
render() {
const classes = makeStyles({
table: {
minWidth: 650,
},
});
if (this.state.rows.length > 0){
return (
<TableContainer component={Paper}>
<Table className={classes.table} aria-label="simple table">
<TableHead>
<TableRow>
<TableCell>Your personal reservations</TableCell>
<TableCell align="right">Title</TableCell>
<TableCell align="right">From </TableCell>
<TableCell align="right">To </TableCell>
</TableRow>
</TableHead>
<TableBody>
{ this.state.rows.map((row) => (
<TableRow key={row.title}>
<TableCell component="th" scope="row">
{row.title}
</TableCell>
<TableCell align="right">{row.from}</TableCell>
<TableCell align="right">{row.to}</TableCell>
</TableRow>
)) }
</TableBody>
</Table>
</TableContainer>
)
} else {
return (
<div> {`You have no active reservations, ${JSON.parse(localStorage.getItem('user')).username}!`} </div>
)
};
}
}
export default ReservationsTable;
Я старался обращать внимание на каждую деталь, например, не изменять состояние напрямую и все такое, но данные таблицы все равно не визуализируются, что делает меня безумным, так как данные быть доступным в состоянии: журнал обратного вызова после setState:
данные журнала массива
отображаемая страница