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

React Bootstrap卡片组件集成问题:实现每行4张卡片时出现编译语法错误

语法错误原因分析

我来帮你拆解下问题:你的代码里有两个核心语法问题导致编译失败,还有个逻辑偏差:

  1. 括号/大括号不匹配:在props.dishes.map(d => (之后,你嵌套了Array.from({ length: 4 }).map(...),但没给这个内层map和外层箭头函数闭合对应的)和},直接跳到了: null,导致解析器找不到预期的},触发了Unexpected token错误。
  2. 缺失组件导入:你用了Row和Col组件,但没从react-bootstrap导入它们,这也是后续运行会报错的点。
  3. 逻辑偏差:Array.from({ length: 4 }).map(...)会把同一个菜品重复渲染4次,这显然不是你想要的「每行4张不同卡片」的效果。

正确代码方案(实现每行4张卡片布局)

下面是修复后的代码,我用React Bootstrap的Grid系统实现了响应式的每行4张卡片布局:

import { connect } from 'react-redux';
import { Link } from 'react-router-dom';
// 补充导入Row和Col组件
import { Card, Button, Row, Col } from 'react-bootstrap';

const MyDishes = props => {
  // 处理无菜品的空状态
  if (props.dishes.length === 0) {
    return <p>暂无菜品</p>;
  }

  // 用Grid系统自动排列卡片,实现每行4张的响应式布局
  const dishCards = (
    <Row xs={1} md={4} className="g-4">
      {props.dishes.map(d => (
        <Col key={d.id}>
          <Card>
            <Card.Img variant="top" src={d.attributes.picture} />
            <Card.Body>
              <Card.Title>{d.attributes.name}</Card.Title>
              <Card.Text>
                Possibly some text here
              </Card.Text>
              <Link to={`/dishes/${d.id}`}>
                <Button variant="primary">查看详情</Button>
              </Link>
            </Card.Body>
          </Card>
        </Col>
      ))}
    </Row>
  );

  return dishCards;
};

const mapStateToProps = state => {
  return { dishes: state.myDishes };
};

export default connect(mapStateToProps)(MyDishes);

关键调整说明

  • 语法修复:补全了所有缺失的括号/大括号,导入了Row和Col组件。
  • 布局优化:
    • Row的xs={1} md={4}属性:小屏幕下每行显示1张卡片,中等及以上屏幕自动每行排4张,自动换行。
    • className="g-4"用来设置卡片间的间距,提升视觉舒适度。
    • 直接遍历props.dishes,每个菜品对应一个Col,由React Bootstrap自动处理排版,不用手动循环固定次数。
  • 用户体验优化:增加了无菜品时的提示文本,避免页面空白。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 14:17:39