跟着《React&Redux》204页示例开发时遇TypeError函数错误
Hey there, let's break down why you're running into that TypeError: (0 , _ColorReducer.color) is not a function error when working through the React & Redux book example!
Root Cause Analysis
This error pops up because the color value you're importing from ./ColorReducer isn't recognized as a function. The most common culprits here are mismatched import/export patterns or an incorrect definition of the color reducer itself.
Fix 1: Verify Your ColorReducer Export/Import
First, double-check how you're exporting the color reducer in ColorReducer.js:
If you're using a named export, your reducer file should look like this:
import * as C from "./Constants"; // Named export for the color reducer export function color(state = {}, action) { switch(action.type) { case C.ADD_COLOR: return { id: action.id, title: action.title, color: action.color, rating: 0, timestamp: action.timestamp }; case C.RATE_COLOR: return state.id === action.id ? {...state, rating: action.rating} : state; default: return state; } }Then your import in
colorsReduceris correct asimport { color } from "./ColorReducer".If you used a default export in
ColorReducer.js(likeexport default color), your import needs to drop the curly braces:// Correct import for default export import color from "./ColorReducer";Using curly braces for a default export is a super common mistake that triggers this exact error.
Fix 2: Ensure the color Reducer is Properly Defined
Make sure color is actually a function, not an object or variable. For example, avoid typos like:
// Wrong: this is an object, not a reducer function export const color = { ... };
Your color reducer needs to follow the standard Redux reducer pattern: accept state and action parameters, and return a new state based on the action type.
Corrected colorsReducer Example
Here's how your combined reducer should look once the import/export is fixed (note the map call for the RATE_COLOR case, which you had truncated):
import React from "react"; import * as C from "./Constants"; import { color } from "./ColorReducer"; export const colorsReducer = (state = [], action) => { switch (action.type) { case C.ADD_COLOR: return [...state, color({}, action)]; case C.RATE_COLOR: // Use map to update the specific color in the array return state.map(colorItem => color(colorItem, action)); default: return state; } };
Quick Checklist
- Confirm
coloris exported as either a named or default export, and your import matches that pattern. - Double-check that
coloris defined as a function inColorReducer.js. - Ensure you're passing the correct arguments (
stateandaction) when callingcolor()in yourcolorsReducer.
内容的提问来源于stack exchange,提问作者Roberto

