使用 React-Modal 传递道具 (img url ) ||类型错误:无法读取未定义的属性(读取"映射")



当我尝试运行此代码时,会出现以下错误:

类型错误:无法读取未定义的属性(读取"映射"(

此代码应返回图像模态,但会引发错误。我不明白为什么在映射函数中会出现这个错误。

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

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;

首先检查您的数组,然后通过它进行映射:

<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>

最新更新