You need to enable JavaScript to run this app. React.js中API获取的商品价格修改后刷新页面留存问题求助
优惠活动
大模型
产品
解决方案
定价
更多

React.js中API获取的商品价格修改后刷新页面留存问题求助

问题原因

  • 本地存储未关联商品ID:所有商品共用同一个price键存储,修改不同商品会互相覆盖,也无法对应到具体商品。
  • 刷新后API原始数据覆盖修改值:App组件每次刷新都会拉取API的原始商品数据,没有把本地存储的修改过的价格合并到全局商品数据中。
  • 输入框为非受控组件:用了defaultValue只会在组件首次渲染时赋值,后续state的price更新不会同步到输入框显示。
  • 价格显示未绑定state:含税价格的展示用的是props传入的原始商品价格,输入修改时不会实时更新。

修复步骤

1. 修改ProductsDetails组件

调整存储逻辑关联商品ID,将输入框改为受控组件,价格展示绑定state:

// 修改componentDidMount,读取当前商品对应的存储价格
componentDidMount() {
  const currentProduct = this.props.products.find(p => p.id === Number(this.state.id))
  const savedPrice = localStorage.getItem(`price_${this.state.id}`)
  const initPrice = savedPrice ? savedPrice : currentProduct.price
  this.setState({price: initPrice});
}

// 修改updatePrice,存储键关联商品ID
updatePrice = (e) => {
  localStorage.setItem(`price_${this.state.id}`, e.target.value)
  this.setState({
    price: e.target.value
  });
};

// 修改render中的输入框和价格展示部分
render() {
  // ...原有逻辑不变
  return (
    // ...原有结构不变
    <input
      name="price"
      className="input__price"
      type="text"
      // 替换defaultValue为value,绑定state
      value={Number(this.state.price).toFixed(2)}
      onChange={this.updatePrice}
    />
    <p>
      Price (including VAT):{" "}
      // 替换listProduct.price为state中的price计算
      {Number(this.state.price * 1.2).toFixed(2)} €
    </p>
    // ...原有结构不变
  )
}

2. 修改App组件

拉取API数据后合并本地存储的修改价格,保证刷新后全局商品数据是修改后的值:

useEffect(() => {
  axios.get("https://fakestoreapi.com/products?limit=7").then((res) => {
    setIsLoaded(true);
    // 合并本地存储的修改价格
    const mergedProducts = res.data.map(product => {
      const savedPrice = localStorage.getItem(`price_${product.id}`)
      return savedPrice ? {...product, price: Number(savedPrice)} : product
    })
    setProductsData(mergedProducts);
  },
  (error) => {
    setIsLoaded(true);
    setError(error);
  }
  );
}, []);

修改完成后即可实现修改价格刷新页面不丢失的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 00:36:03