You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Chakra-UI将API获取的数据渲染为4列及以上的网格布局

问题原因

你将SimpleGrid组件写在了stores.map遍历逻辑的内部,这会导致每一个商品数据都单独生成一个仅包含1个元素的4列网格,最终所有内容就会呈现单列纵向排列的效果。

修正方案

把SimpleGrid移到遍历逻辑的外层,让所有商品卡片作为同一个网格容器的直接子元素即可实现4列布局。
修正后的代码如下:

import axios from "axios";
import { Box, Image, Heading, Text, SimpleGrid } from "@chakra-ui/react";
import { MdHeadset, MdEmail, MdLocationOn } from "react-icons/md";
import { BsFillBriefcaseFill } from "react-icons/bs";

const Stores = ({stores}) => { 
  if(!stores){ 
    return <div>Loading...</div> 
  }
  console.log(stores);
  return (
    // SimpleGrid移到map外层
    <SimpleGrid columns={4} spacing={10} pl={6}>
      {stores.map((store, index) => (
        // 遍历生成单个卡片,添加唯一key属性
        <Box height="400px" key={index}>
          <Text>{store.name}</Text>
          <Image src={store.imageUrl} alt={store.name} />
          <Heading>{store.vBucks}</Heading>
        </Box>
      ))}
    </SimpleGrid>
  )
}

Stores.getInitialProps = async (ctx) => {
  try {
    const res = await axios.get("https://api.fortnitetracker.com/v1/store", { 
      headers: {
        'TRN-Api-Key' : 'XXX',
        'Access-Control-Allow-Origin' : true,
      }
    });
    const stores = res.data;
    console.log(stores)
    return { stores };
  } catch (error) {
    return { error };
  }
};

export default Stores;

额外优化建议

可以给SimpleGrid添加minChildWidth属性实现响应式布局,比如设置为minChildWidth="240px",当屏幕宽度不足时会自动减少列数,适配移动端展示效果。


内容的提问来源于stack exchange,提问作者MatDoak

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 03:39:03