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

如何通过单个React类组件与数据表实现两个邮轮进化页面?

解决方案:拆分Evolution页面数据到两个子页面

1. 在Evolution组件的state中定义数据字段

直接在类组件的构造函数里初始化state,给evo1Data和evo2Data设置空数组初始值,分别用来存储两个页面的数据:

constructor(props) {
  super(props);
  this.state = {
    evo1Data: [], // 对应id 1-6的船只数据
    evo2Data: []  // 对应id 7-12的船只数据
  };
}

2. 根据id范围拆分数据并更新state

方案一:获取全量数据后前端过滤

如果你已经拿到了所有船只的完整数据(比如命名为allShipsData),用数组的filter方法根据id范围拆分,再通过this.setState更新对应状态:

componentDidMount() {
  // 替换成你实际获取全量数据的逻辑(接口请求/本地导入都可以)
  fetch('/api/classic-ships')
    .then(res => res.json())
    .then(allShipsData => {
      const evo1 = allShipsData.filter(ship => ship.id >= 1 && ship.id <= 6);
      const evo2 = allShipsData.filter(ship => ship.id >= 7 && ship.id <= 12);
      
      this.setState({
        evo1Data: evo1,
        evo2Data: evo2
      });
    })
    .catch(err => console.error('数据获取失败:', err));
}

方案二:分两次请求对应id范围的数据(后端支持的话更高效)

如果后端接口支持按id范围筛选,直接分别请求两个页面的数据,减少前端处理开销:

componentDidMount() {
  // 请求evolution-part1的数据(id 1-6)
  fetch('/api/classic-ships?id_min=1&id_max=6')
    .then(res => res.json())
    .then(evo1Data => this.setState({ evo1Data }))
    .catch(err => console.error('evo1数据请求失败:', err));

  // 请求evolution-part2的数据(id 7-12)
  fetch('/api/classic-ships?id_min=7&id_max=12')
    .then(res => res.json())
    .then(evo2Data => this.setState({ evo2Data }))
    .catch(err => console.error('evo2数据请求失败:', err));
}

配合ClassicShips组件渲染对应页面

在Evolution组件的render方法里,根据当前路由判断要渲染哪个数据集,把对应数据传给ClassicShips组件:

render() {
  const { evo1Data, evo2Data } = this.state;
  // 通过路由路径判断当前是哪个页面
  const isPart1 = this.props.match.path === '/evolution-part1';
  const renderData = isPart1 ? evo1Data : evo2Data;

  return (
    <div className="evolution-page">
      <ClassicShips ships={renderData} />
    </div>
  );
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 20:35:29