无法读取未定义的属性(读取"map"),同时在下一个js中挂载组件



我的产品组件中有以下配置:

import axios from "axios";
import React, { useEffect } from "react";
import { useDispatch } from "react-redux";
import { connect } from "react-redux";
import productsAction from "../redux/actions/productsAction";
import { FETCH_PRODUCTS } from "../redux/actions/types";
function products({ products }) {
const dispatch = useDispatch();
useEffect(() => {
axios.get("http://localhost:8197/Plant/GetPlant").then(({ data }) =>
dispatch({
type: FETCH_PRODUCTS,
payload: data,
})
);
}, []);
return (
<div>
{products.map((product, index) => (
<h1 key={index}>{product.title}</h1>
))}
</div>
);
}
export const mapStateToProps = (state) => {
return {
products: state.products.products,
};
};
export default connect(mapStateToProps)(products);

一切都还好,但当我运行项目时,它抛出了一个错误:

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

当我用redux devtools检查项目时,products数组等于[]。

如何修复错误?

最有效的方法是添加loading stateloader。当axios发送请求时,将loading state设置为true,并且当接收到数据时,将其设置回false

loading statetrue时,在您的页面上显示一个loader

const Products = () => {
const [loading, setLoading] = useState(false)
useEffect(() => {
setLoading(true) // <------Set loading state to true------>
axios.get("http://localhost:8197/Plant/GetPlant").then(({ data }) =>
dispatch({
type: FETCH_PRODUCTS,
payload: data,
})
);
setLoading(false) // <---------Set loading state to false after data is retreived------->
}, []);
if(loading) {
return <p>Loading...</p> // <-----Return a loading component which shows a loader when loading state is true
}
return (
<div>
{products && products.map((product, index) => (
<h1 key={index}>{product.title}</h1>
))}
</div>
);
}

您的代码在初始化之前正在访问产品。现在可以做的是条件渲染。

<div>
{products && products.map((product, index) => (
<h1 key={index}>{product.title}</h1>
))}
</div>

您在API调用之前呈现产品,该调用肯定会返回未定义。

所以写

{
products?.map((product, index) => (
<h1 key={index}>{product.title}</h1>
))
}

{
!!products && products.map((product, index) => (
<h1 key={index}>{product.title}</h1>
))
}

最新更新