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

Redux执行每个Action后Store被清空,求排查问题原因

Why Your Redux Store Is Getting Overwritten on Each Dispatch

Hey there! I see exactly what's going on here—your reducer is replacing the entire state instead of updating just the part you need. Let's break this down:

The Root Cause

In Redux, reducers are supposed to return a new state object that includes both the existing state data and the updated values. Right now, your reducer code for WRITE_PRODUCT is doing this:

case 'WRITE_PRODUCT': 
  console.log("WRITE PRODUCT ACTION: ", action); 
  console.log("state: ",state); 
  return { productID: action.id };

When you return { productID: action.id }, you're discarding every other piece of data that was already in the state. That's why your entire store gets emptied except for the new productID—you're replacing the whole state instead of merging the update into it.

The Fix

Use the spread operator (...) to copy all existing state properties first, then override the productID with the new value. Here's the corrected reducer code:

case 'WRITE_PRODUCT': 
  console.log("WRITE PRODUCT ACTION: ", action); 
  console.log("state: ",state); 
  // Merge existing state with the updated productID
  return {
    ...state,
    productID: action.id
  };

This way, you preserve all the existing state data and only update the productID field.

A Quick Note on Immutable Updates

Redux relies on immutable state updates—you never modify the original state object directly, you always return a new one. The spread operator is a simple way to do this for flat state structures. If your state has nested objects later on, you'll need to apply the same pattern to those nested levels, or use a library like Immer to simplify the process.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 06:38:04