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

React API请求组件状态提升:如何将接口返回的itemCount传递给父组件

解决方案

核心逻辑说明

你不需要绑定任何DOM交互事件来传递itemCount,因为这个值的更新时机是API请求成功后,直接在对应逻辑节点调用父组件传入的回调函数即可。

具体修改步骤

1. 修改ApiTest组件代码

有两种可选的实现方式,选其中一种即可:

方式1:请求成功后直接传递

在axios请求成功的then回调中,直接调用父组件传入的items方法:

const ApiTest = (props) => {  
  const [product, setProducts] = useState([]);  
  const [itemCount, setItemCount] = useState();  
  // 注意:这里要把limit、offset加入依赖数组,否则翻页时不会重新发起请求
  useEffect(() => {
    const options = {
      method: "GET",
      url: "https://asos2.p.rapidapi.com/products/v2/list",
      params: {
        store: "US",
        offset: props.offset,
        categoryId: "4209",
        limit: props.limit,
        country: "US",
        sort: "freshness",
        currency: "USD",
        sizeSchema: "US",
        lang: "en-US",
      },
      headers: {
        "x-rapidapi-key": "",
        "x-rapidapi-host": "",
      },
    };
    axios
      .request(options)
      .then(function (response) {
        setProducts(response.data.products);
        const newItemCount = response.data.itemCount;
        setItemCount(newItemCount);
        // 直接调用父组件传入的回调传递数据
        props.items(newItemCount);
        console.log(response.data);
      })
      .catch(function (error) {
        console.error(error);
      });
  }, [props.limit, props.offset]); // 新增依赖
  return (
    <div>
      <div className={classes.container}>
        {product.map((product) => (
          <ProductCard
            key={product.id}
            img={product.imageUrl}
            name={product.name}
            price={product.price.current.text}
          />
        ))}
      </div>
    </div>
  );
};

方式2:监听itemCount变化后传递

如果你的itemCount可能有其他修改场景,可以单独加一个useEffect监听它的变化,变化时自动传递给父组件:

// 在ApiTest组件内新增这个useEffect
useEffect(() => {
  // 仅当itemCount有值时调用回调
  if(itemCount !== undefined) {
    props.items(itemCount);
  }
}, [itemCount, props.items])

2. 修复Products组件的已知问题

你当前的翻页按钮是submit类型,点击会触发表单默认提交行为导致页面刷新,需要修改:

const loadMoreHandler = (e) => {
  // 阻止表单默认提交
  e.preventDefault();
  setLimit(limit + 48);
  setOffset(offset + 48);
};

// 按钮部分修改为
<button onClick={loadMoreHandler} type="button">
  Previous Page
</button>
<button onClick={loadMoreHandler} type="button">
  Next Page
</button>

修改完成后只要ApiTest请求成功,就会自动把itemCount传递给父组件Products的对应状态。

内容的提问来源于stack exchange,提问作者simon sjöö

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 08:45:00