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

React JS报错:Unhandled Rejection (Error),SET_CARS动作致Reducer返回undefined

Fixing "Reducer 'cars' returned undefined" for Action "SET_CARS"

Hey there, let's break down why you're seeing that error and fix it step by step:

1. Typo in Redux's combineReducers

First off, you have a critical spelling mistake in your reducer file: combineReducer should be combineReducers (plural form). Redux exports this function with an 's' at the end, so using the wrong name will break how your reducers are registered. Update that line to:

import { combineReducers } from "redux";

2. Undefined action.items Triggering the Reducer Error

The core issue here is that when the SET_CARS action is dispatched, action.items is undefined—so your reducer returns undefined instead of a valid state. Let's fix the root causes:

  • Spelling errors in component: You misspelled "transmission" as tansmition (both in the component state and fetch URL). This invalid query param will likely make your backend return a response where json.results doesn't exist. Correct the spelling everywhere:
    constructor() {
      super();
      this.state = { transmission: "" }; // Fixed spelling
    }
    search() {
      let { transmission } = this.state; // Fixed spelling
      // Removed extra space after `?` (would break the URL)
      const url = `http://localhost:4000/vehicles/?transmission=${transmission}`;
      fetch(url, { method: 'GET' })
        .then(response => {
          // First check if the request succeeded
          if (!response.ok) throw new Error(`Request failed: ${response.status}`);
          return response.json();
        })
        .then(json => {
          // Guard against missing `results` property
          this.props.setCars(json.results || []);
        })
        .catch(err => {
          // Handle errors to avoid unhandled rejections
          console.error('Search failed:', err);
          // Reset to empty array on error to keep state valid
          this.props.setCars([]);
        })
    }
    
  • Unhandled fetch errors: Your original fetch call didn't handle network failures or bad HTTP statuses. Adding a catch block prevents unhandled rejections, and using json.results || [] ensures you never pass undefined to setCars.

3. Missing Redux Connection for the Component

Your SearchCars component isn't connected to Redux, which means this.props.setCars doesn't exist (this would throw another error even after fixing the above). Connect the component using Redux's connect function:

import { connect } from 'react-redux';
import { setCars } from '../actions';

// ... your component class code ...

// Map the action creator to component props
export default connect(null, { setCars })(SearchCars);

4. Strengthen Reducer Logic (Optional but Safe)

While your reducer logic is mostly correct, adding a guard clause ensures it never returns undefined, even if unexpected data comes through:

function cars(state = [], action) {
  switch (action.type) {
    case SET_CARS:
      // Fall back to current state if action.items is not a valid array
      return Array.isArray(action.items) ? action.items : state;
    default:
      return state;
  }
}

Putting all these fixes in place will resolve the undefined reducer error and get your car search functionality working properly.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:56:01