【问题标题】:getting empty array data after mapping the data in table映射表中的数据后获取空数组数据
【发布时间】:2021-05-13 22:31:55
【问题描述】:

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

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>
  );
}

【问题讨论】:

  • 你能检查你的 API 请求的响应吗?你得到什么回应?

标签: reactjs axios react-hooks material-ui


【解决方案1】:

使用 async 并等待它的工作正常,通常当我们调用 get 请求时,我们应该处理 await 以获取所有数据,这里是我调用 get request 的代码。

 const API = "http://localhost:8080/getForm";
  useEffect(() => {
    const fetchData = async () => {
      const result = await axios(API);

      setForm(result.data);
    };
    fetchData();
  }, []);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-03
    • 1970-01-01
    • 1970-01-01
    • 2020-11-07
    • 1970-01-01
    • 2021-09-30
    • 2021-02-27
    相关资源
    最近更新 更多