Redux执行每个Action后Store被清空,求排查问题原因
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

