尽管处于状态

时间:2020-04-27 09:35:20

标签: reactjs rest rendering

我想问你为什么我的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&nbsp;</TableCell>
            <TableCell align="right">To&nbsp;</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之后的回调日志:

Array Log data

Rendered page

2 个答案:

答案 0 :(得分:0)

缺少退货是此错误的可能原因

{ this.state.rows.map((row) => {
  return(
  ...
)}

答案 1 :(得分:0)

作为未来读者的解决方案... 代码的唯一缺陷是给forEach()的异步回调。作为内置工具,forEach映射并非旨在获取异步回调,因此循环在数组填充之前完成,并且在调用setState时绕过了React.JS自动渲染,因为数据稍后输入到状态对象中。