React组件间传值实现:Store组件传props给Related组件并在componentDidMount调用
解决方法
你只需要在Related类组件中通过this.props访问父组件传入的属性即可,修改两处代码即可生效:
- 修改
Related组件constructor中的state初始化代码,通过构造函数入参props访问传入的CatID - 修改
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
相关产品推荐
相关产品推荐

