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

点击按钮通过API更新Redux Store异常问题求助

问题原因与解决方法

根本原因

你使用的<a>标签自带页面跳转行为:点击时会先执行handleAction更新Redux Store,但紧接着浏览器会加载/shop页面,导致整个应用重新初始化,Redux Store里刚更新的数据被重置,所以控制台中product.title的值刚出现就消失。

解决方法

根据你的路由类型,选择以下任意一种方案:

方案1:使用React Router的单页路由组件(推荐)

如果你的项目用了React Router,直接替换<a>为Link组件,它只会触发单页路由切换,不会刷新整个页面,Redux Store状态会被保留:

// 先导入Link组件
import { Link } from 'react-router-dom';
import { useEffect, useState } from "react";
import "../styles/BestSellers.css";
import { useDispatch } from "react-redux";
import { setItem } from "../features/ProductState";

function BestSellers() {
  const [products, setProducts] = useState([]);
  const [count, setCount] = useState(10);
  const dispatch = useDispatch();

  useEffect(() => {
    fetch(`https://dummyjson.com/products?limit=${count}`)
      .then((res) => res.json())
      .then((data) => {
        setProducts(data.products);
      });
  }, [count]);

  const loadMore = () => {
    setCount((prevCount) => prevCount + 5);
  };

  const handleAction = (product) => {
    dispatch(
      setItem({
        title: product.title,
        image: product.image,
        price: product.price,
      })
    );
  };

  return (
    <div className="container">
      <div className="products">
        {products.map((product) => (
          <Link
            onClick={() => handleAction(product)}
            className="link"
            to="/shop"
            key={product.id}
          >
            <div className="product">
              <h5>{product.title}</h5>
              <p>English Department</p>
              <span className="prices">
                <h4 className="discount">$16.48</h4>
                <h4>${product.price}</h4>
              </span>
            </div>
          </Link>
        ))}
      </div>
      <button onClick={loadMore} className="btn">
        LOAD MORE PRODUCTS
      </button>
    </div>
  );
}

export default BestSellers;

方案2:阻止<a>标签的默认跳转行为

如果必须保留<a>标签,在点击事件中阻止浏览器的默认跳转,确保Redux Store更新完成后再手动控制跳转:

import { useEffect, useState } from "react";
import "../styles/BestSellers.css";
import { useDispatch } from "react-redux";
import { setItem } from "../features/ProductState";

function BestSellers() {
  const [products, setProducts] = useState([]);
  const [count, setCount] = useState(10);
  const dispatch = useDispatch();

  useEffect(() => {
    fetch(`https://dummyjson.com/products?limit=${count}`)
      .then((res) => res.json())
      .then((data) => {
        setProducts(data.products);
      });
  }, [count]);

  const loadMore = () => {
    setCount((prevCount) => prevCount + 5);
  };

  const handleAction = (product, e) => {
    e.preventDefault(); // 阻止默认页面跳转
    dispatch(
      setItem({
        title: product.title,
        image: product.image,
        price: product.price,
      })
    );
    // 手动触发跳转,可根据需要调整时机
    window.location.href = '/shop';
  };

  return (
    <div className="container">
      <div className="products">
        {products.map((product) => (
          <a
            onClick={(e) => handleAction(product, e)}
            className="link"
            href="/shop"
            key={product.id}
          >
            <div className="product">
              <h5>{product.title}</h5>
              <p>English Department</p>
              <span className="prices">
                <h4 className="discount">$16.48</h4>
                <h4>${product.price}</h4>
              </span>
            </div>
          </a>
        ))}
      </div>
      <button onClick={loadMore} className="btn">
        LOAD MORE PRODUCTS
      </button>
    </div>
  );
}

export default BestSellers;

补充说明

如果是跨页面跳转(非单页应用),需要给Redux配置持久化(比如使用redux-persist),否则页面刷新后Store状态会丢失。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 03:13:22