【问题标题】:Passing Props (img url ) using React-Modal || TypeError: Cannot read properties of undefined (reading 'map')使用 React-Modal 传递道具 (img url) || TypeError:无法读取未定义的属性(读取“地图”)
【发布时间】:2022-01-14 03:59:31
【问题描述】:

当我尝试运行这段代码时,它给了我这个错误:

TypeError: Cannot read properties of undefined (reading 'map')

此代码应返回图像模式,但会引发错误。我不明白为什么我在映射函数中收到此错误。

在 API 调用之前我的 deps 数组是否为空,因此使用 deps.map 会导致错误?还是cookie问题?

DepositRecord.js

import React, { useEffect, useState } from "react";
import { Button, ButtonToolbar, Table } from "react-bootstrap";
import Cookies from 'universal-cookie';
import AddDepositModal from "./AddDeposiModal";

const DepositRecord = () => {
  const [deps, setDeps] = useState([]);
  const [visibleModal, setVisibleModal] = useState(false);
  const [depImage, setDepImage] = useState(null);

    useEffect(() => {
    loadDepsHandler();
    }, []);

  const loadDepsHandler = () => {
    const myRequest = new Request("https://XXXXXXXXXX/DepositRecords", {
      method: "GET",
      cache: "default",
      headers: { Authorization: `Bearer ${cookies.get('userToken')}` },
    });
    debugger;
    fetch(myRequest)
      .then((res) => res.json())
      .then((data) => {
        const { results } = data;
        setDeps(results);
      })
      .catch((err) => console.log(err));
  };

  const setDepHandler = (id) => {
    const dep = deps.find((a) => a.id.value === id);
    debugger;
    setDepImage(dep.picture.large);
    setVisibleModal(true);
  };

  return (
    <div>
      <h3>Customer's Deposit Record</h3>
      <br />

      <Table className="mt-4" striped bordered hover size="sm">
        <thead>
          <tr>
            <th>Deposit id</th>
            <th>user name</th>
            <th>img attachment</th>
          </tr>
        </thead>
        <tbody>
          {deps.map((item) => (
            <tr key={item.id.name}>
              <td>{item.id.name}</td>
              <td>{item.value}</td>
              <td>
                <ButtonToolbar>
                  <Button
                    variant="primary"
                    onClick={() => setDepHandler(item.id.value)}
                  >
                    image attachment
                  </Button>
                </ButtonToolbar>
              </td>
            </tr>
          ))}
        </tbody>
      </Table>
      {visibleModal && (
        <AddDepositModal
          show={visibleModal}
          onHide={() => setVisibleModal(false)}
          image={depImage}
        />
      )}
    </div>
  );
};

export default DepositRecord;

AddDepositModal.js

import React from "react";
 import { Button, Modal } from "react-bootstrap";

 const AddDepositModal = ({ show, onHide, image }) => {
  return (
    <Modal show={show} onHide={onHide}>
      <Modal.Header closeButton>
        <Modal.Title id="contained-modal-title-vcenter">
          Deposit Record
        </Modal.Title>
      </Modal.Header>
      <Modal.Body>
        <img src={image} width={700} height={1100} alt={image} />
      </Modal.Body>
      <Modal.Footer>
        <Button variant="danger" onClick={onHide}>
          Close
        </Button>
      </Modal.Footer>
    </Modal>
  );
};
export default AddDepositModal;

【问题讨论】:

  • .then((res) =&gt; res.json()) .then((data) =&gt; { console.log(data) }) 你得到了什么?
  • 编译失败。

标签: javascript reactjs mapping bootstrap-modal


【解决方案1】:

首先检查您的数组,然后对其进行映射:

       <tbody>
      {deps.length > 0 && deps.map((item) => (
        <tr key={item.id.name}>
          <td>{item.id.name}</td>
          <td>{item.value}</td>
          <td>
            <ButtonToolbar>
              <Button
                variant="primary"
                onClick={() => setDepHandler(item.id.value)}
              >
                image attachment
              </Button>
            </ButtonToolbar>
          </td>
        </tr>
      ))}
    </tbody>

【讨论】:

  • TypeError: 无法读取未定义的属性(读取“长度”)
  • 首先,console.log 像这样记录你的结果,确保你得到数组形式的数据! const loadDepsHandler = () => { const myRequest = new Request("XXXXXXXXXX/DepositRecords", { method: "GET", cache: "default", headers: { Authorization: Bearer ${cookies.get('userToken')} }, });调试器; fetch(myRequest) .then((res) => res.json()) .then((data) => { const { results } = data; console.log(results) setDeps(results); }) .catch( (err) => console.log(err)); };` `
  • 无法从 Fetch 方法获取数组数据!!!我认为这是我的授权:XXXX 问题
  • 在添加标题之前,我遵循此链接的解决方案是可行的:{ Authorization: Bearer ${cookies.get('userToken')} stackoverflow.com/questions/70692322/…
  • 使用错误也表示没有数据,所以一旦你得到数据,你可以像我回答的那样映射它。你也可以通过浏览器检查你的请求状态,看看你有哪种状态可以帮助您修复错误。
猜你喜欢
  • 2019-03-18
  • 2021-09-24
  • 2020-08-04
  • 1970-01-01
  • 1970-01-01
  • 2017-03-26
  • 2021-09-09
  • 2020-09-16
  • 2020-03-09
相关资源
最近更新 更多