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

React组件间传值实现:Store组件传props给Related组件并在componentDidMount调用

解决方法

你只需要在Related类组件中通过this.props访问父组件传入的属性即可,修改两处代码即可生效:

  1. 修改Related组件constructor中的state初始化代码,通过构造函数入参props访问传入的CatID
  2. 修改componentDidMount中的接口请求参数,通过this.props.CatID获取传入的分类ID

修改后的核心代码片段

Related.js 构造函数部分
constructor(props) {
  super(props);

  this.state = {
    data: [],
    visible: 6,
    isLoading: true,
    dataLoaded: false,
    rec: props.CatID, // 从构造函数入参props中获取传入的CatID
  };
  this.loadMore = this.loadMore.bind(this);
}
Related.js componentDidMount部分
async componentDidMount() {
  const url = "https://localhost:3030/api/v5/web/related";
  const postBody = {
    category_id: this.props.CatID, // 通过this.props访问传入的CatID
    offer_type: "",
  };
  // 后续请求逻辑保持不变即可
}

可选优化

因为Store组件中的category_id是异步请求接口后才赋值的,初始渲染时catId可能为undefined,你可以修改Store.js中Related组件的渲染逻辑,等catId有有效值后再渲染组件,避免无效请求:

{catId && <Related CatID={catId}/>}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 02:09:03