【发布时间】:2021-09-01 12:22:56
【问题描述】:
我正在尝试使用来自 db 的数据来渲染卡片。当我运行代码时,我收到错误“无法读取未定义的属性“映射””。有任何想法吗?我做错了什么
const ProductList = () =>
{
const [prodList, setProdList] = useState();
const [ pass, setPass] = useState();
const getitems = async () => {await axios.get('http://localhost:3001/services').then((response) => setPass(response.data));}
useEffect(() => {
getitems().then((pass) => setProdList(pass));
}, []);
return (
<>
<Container maxWidth={false}>
<ProductListToolbar />
<Box sx={{ pt: 3 }}>
<Grid
container
spacing={3}
>
{prodList.map((product) => (
<Grid
item
key={product.serviceID}
lg={4}
md={6}
xs={12}
>
<ProductCard product={product} />
</Grid>
))}
</Grid>
</Box>
</Container>
</>)}
export default ProductList;
【问题讨论】:
-
将初始值作为
[]传递给您的状态。const [prodList, setProdList] = useState([]); -
这里还有 Productcard 组件:codesandbox.io/s/objective-rgb-occ48?file=/src/App.js
-
@Shyam 我得到了同样的错误。另外它说“(匿名函数)> 21 | getitems().then((pass) => setProdList(pass));”
-
已添加我的答案!请看一看。
标签: reactjs