Redux Store仅返回Null值排查:Reducer正常但combineReducers异常
Let's break down what's happening here and fix it step by step:
First, let's recap your scenario:
- Your standalone
Reducer_placeordercorrectly returns theaction.payloaddata when thePLACE_ORDERaction is dispatched. - But when you combine it using
combineReducers, the Redux Store starts returning null instead of your expected data.
Here's Your Code for Reference:
Reducer_placeorder.js
export default function(state =[], action) { switch (action.type) { case "PLACE_ORDER": console.log("inside reducer") console.log(action.payload)//returns data that is passed return action.payload; default: console.log("default") return state; } }
Reducers/index.js
import { combineReducers} from "redux"; import reducer_placeorder from "./Reducer_placeorder"; const rootReducer = combineReducers({ data: reducer_placeorder, })
The Root Cause
The issue isn't with combineReducers itself—it's with how you're accessing the state from your Redux Store.
When you use combineReducers, it creates a single root state object where each key maps to the state managed by the corresponding reducer. In your case, your reducer_placeorder's state is now nested under the data key of the root state.
If you're trying to access the order data directly from the root state (e.g., useSelector(state => state) instead of useSelector(state => state.data)), you'll either get the full root object (and might misinterpret it as null) or end up with unexpected null values.
The Fixes
Access the correct nested state path
In your components, make sure you're selecting thedatakey from the root state to get the data managed by yourreducer_placeorder:// Using useSelector (React-Redux) const orderData = useSelector(state => state.data);Verify your Store setup
Double-check that you're creating your Store with the rootReducer, not the standalone reducer:import { createStore } from 'redux'; import rootReducer from './Reducers/index'; const store = createStore(rootReducer);Confirm action payload validity
You already confirmed thataction.payloadhas actual data when logged in the reducer, so this is probably not the issue—but just to be thorough: ensure that the payload you're dispatching isn't accidentally null at the point of dispatch.
Quick Note on combineReducers
Think of combineReducers as an organizer: it takes all your individual reducer states and puts them into a single object, with each reducer's state stored under the key you specify. So your root state structure looks like this after combining:
{ data: [] // Initial state from reducer_placeorder, then becomes action.payload after PLACE_ORDER }
That's why you need to access state.data to get the actual order data!
内容的提问来源于stack exchange,提问作者muqsith

