我无法解决"Uncaught TypeError: Cannot read properties of undefined (reading 'map')",尝试创建过滤器级联按钮



我尝试了各种解决方案,但都无法解决。有人能帮我吗?我正在尝试创建按钮,通过单击A列中的按钮来过滤B列中的按键。现在,这些按钮正在左侧菜单(仓库(中呈现。但当我点击一个仓库时,右栏(按钮(中的相应画作没有渲染,我得到了以下错误。

const Separator = () => {
// Function Component
// for warehouse - this works
const [warehouseList, setWarehouseList] = useState([]);
// export component
useEffect(() => {
// right when the Separator list renders, we run this function
axios
.get(API_BASE_URL)
.then((res) => {
setWarehouseList(res.data);
console.log("printing warehouses -- ");
console.log(res.data);
})
.catch((err) => console.log(err.res));
}, []); // this should return all the warehouses
// const [_id, setID] = useState([warehouseList._id]);
const [relatedPaintings, setRelatedPaintings] = useState([warehouseList._id]); // passing all warehouses with ids
//const get_id = useRef(relatedPaintings._id);
const paintingButtonItems = [
...new Set(
relatedPaintings._id.map((relatedPaintings) => relatedPaintings.data)
),
];
useEffect(() => {
// right when the Separator list renders, we run this function
//  const id = get_id;
axios
.get(API_BASE_URL + "/" + relatedPaintings)
.then((res) => {
setRelatedPaintings(res.data);
console.log("printing paintings ");
console.log(res.data);
})
.catch((err) => console.log(err.res));
}, [relatedPaintings]); // only return painting for specific warehouse
return (
// return JSX
<>
<table>
<thead></thead>
<tbody>
<tr id="adjustRow">
<td>
<ListGroup className="listWidth">
<ListGroup.Item action variant="warning">
{" "}
<strong> Warehouses </strong>
</ListGroup.Item>
</ListGroup>
{warehouseList.map((warehouse) => {
return <Warehouse key={warehouse._id} warehouse={warehouse} />;
})}
</td>
<td id="adjustTD">
<ListGroup className="listWidth">
<ListGroup.Item action variant="warning">
{" "}
<strong> Paintings </strong>
</ListGroup.Item>
</ListGroup>
{
(paintingButtonItems || []).map((relatedPaintings, id) => {
return (
<Painting
key={relatedPaintings.id}
value={relatedPaintings}
/>
);
})
//paintingList.map(painting => <Painting warehouse={Warehouse._id} painting={painting}/>)         // LOGIC FOR POPULATING THIS IS UP THERE
}
</td>
</tr>
</tbody>
</table>
</>
);
};
export default Separator;

您正试图访问一个未定义值的map属性。之所以会发生这种情况,可能是因为当您试图访问relatedPaintings时,该值未定义。

您可以通过确保在尝试访问其贴图属性之前定义了relatedPaintings来解决此问题。你可以使用这样的条件:

if (relatedPaintings) {
// access the map property here
}

最新更新