簡體   English   中英

未捕獲的類型錯誤:無法讀取未定義的屬性“狀態”-React.js

[英]Uncaught TypeError: Cannot read property 'state' of undefined - React.js

我是 React.js 的絕對初學者。 我檢查了類似的問題並應用了其中一些,但我仍然無法解決問題。 我在下面添加了 .js 文件。 我使用 Django REST API 從我的 Z497757A9C5B2EC17DED656170B5 表中獲取數據並嘗試將數據放入 myC 數據中。 GET 請求給了我一個 JSON 文件,我嘗試將其轉換為合適的數據格式。

import React, {Component} from 'react';
import PropTypes from 'prop-types';
import {makeStyles} from '@material-ui/core/styles';
import Box from '@material-ui/core/Box';
import Collapse from '@material-ui/core/Collapse';
import IconButton from '@material-ui/core/IconButton';
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 Typography from '@material-ui/core/Typography';
import Paper from '@material-ui/core/Paper';
import KeyboardArrowDownIcon from '@material-ui/icons/KeyboardArrowDown';
import KeyboardArrowUpIcon from '@material-ui/icons/KeyboardArrowUp';

const useRowStyles = makeStyles({
  root: {
    '& > *': {
      borderBottom: 'unset',
    },
  },
});

function createData(name, mail, mss) {
  return {
    name,
    mail,
    history: [
      { massage: mss},
    ],
  };
}

function Row(props) {
  const { row } = props;
  const [open, setOpen] = React.useState(false);
  const classes = useRowStyles();

  return (
    <React.Fragment>
      <TableRow className={classes.root}>
        <TableCell>
          <IconButton aria-label="expand row" size="small" onClick={() => setOpen(!open)}>
            {open ? <KeyboardArrowUpIcon /> : <KeyboardArrowDownIcon />}
          </IconButton>
        </TableCell>
        <TableCell component="th" scope="row">
          {row.name}
        </TableCell>
        <TableCell align="right">{row.mail}</TableCell>
      </TableRow>
      <TableRow>
        <TableCell style={{ paddingBottom: 0, paddingTop: 0 }} colSpan={6}>
          <Collapse in={open} timeout="auto" unmountOnExit>
            <Box margin={1}>
              <Typography variant="h6" gutterBottom component="div">
                History
              </Typography>
              <Table size="small" aria-label="purchases">
                <TableHead>
                  <TableRow>
                    <TableCell>İçerik</TableCell>

                  </TableRow>
                </TableHead>
                <TableBody>
                  {row.history.map((historyRow) => (
                    <TableRow key={historyRow.massage}>
                      <TableCell component="th" scope="row">
                        {historyRow.massage}
                      </TableCell>

                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </Box>
          </Collapse>
        </TableCell>
      </TableRow>
    </React.Fragment>
  );
}

Row.propTypes = {
  row: PropTypes.shape({
    name: PropTypes.string.isRequired,
    mail: PropTypes.string.isRequired,
    history: PropTypes.arrayOf(
      PropTypes.shape({
        message: PropTypes.string.isRequired,
      }),
    ).isRequired,
  }).isRequired,
};


function CollapsibleTable(rows) {
  return (
    <TableContainer component={Paper}>
      <Table aria-label="collapsible table">
        <TableHead>
          <TableRow>
            <TableCell />
            <TableCell>Name</TableCell>
            <TableCell align="right">Mail</TableCell>
          </TableRow>
        </TableHead>
        <TableBody>
          {rows.map((row) => (
            <Row key={row.name} row={row} />
          ))}
        </TableBody>
      </Table>
    </TableContainer>
  );
}

const rows = [
  createData('Frozen yoghurt', "metegenez", "selam"),
  createData('Ice cream sandwich', "metegenez", "selam"),
  createData('Eclair', "metegenez", "selam"),
  createData('Cupcake', "metegenez", "selam"),
  createData('Gingerbread', "metegenez", "selam")];

function mapDatasInto() {
    return (
        this.state.data.map(contact => {
          return (
              createData(contact)
          );
        })
    );
  }

class Tablee extends Component {

  constructor(props) {
    super(props);
    this.state = {
      data: [],
      loaded: false,
      placeholder: "Loading"
    };
    this.componentDidMount = this.componentDidMount.bind(this);
    this.mapDatasInto = this.mapDatasInto.bind(this);
  }


  componentDidMount() {
    fetch("api/lead")
        .then(response => {
          if (response.status > 400) {
            return this.setState(() => {
              return {placeholder: "Something went wrong!"};
            });
          }
          console.log(response);
          return response.json();
        })
        .then(data => {
          this.setState(() => {
            return {
              data,
              loaded: true
            };
          });
        });


  }
  mapDatasInto() {
    return (
        this.state.data.map(contact => {
          return (
              createData(contact)
          );
        })
    );
  }

  render() {
    return (CollapsibleTable(mapDatasInto()));
  }
}
export default Tablee;

我使用行進行調試,但是當我使用 state 中的數據時,我得到了這樣的錯誤。 我相信對此有一個簡單的解釋。

Uncaught TypeError: Cannot read property 'state' of undefined
    at mapDatasInto (Table.js:181)
    at Tablee.render (Table.js:242)
    at finishClassComponent (react-dom.development.js:17160)
    at updateClassComponent (react-dom.development.js:17110)
    at beginWork (react-dom.development.js:18620)
    at HTMLUnknownElement.callCallback (react-dom.development.js:188)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:237)
    at invokeGuardedCallback (react-dom.development.js:292)
    at beginWork$1 (react-dom.development.js:23203)
    at performUnitOfWork (react-dom.development.js:22157)

我認為 componentDidMount 中的 fetch('api/lead') 不會返回您要查找的數據。 你可以試試componentDidMount中的console.data,看看是否加載了數據嗎? 如果有數據,則意味着 setState 有問題

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM