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

Redux中dispatch未定义报错咨询:connect注入dispatch差异问题

Why does dispatch is not defined occur in my Redux v3.7.2/react-redux v5.0.5 code?

Let's break down why your first code snippet throws a dispatch is not defined error, while the second one works—this isn't about outdated library versions, but about how connect() injects props into your component.

First, let's recap the core issue

Your first component uses object destructuring to pull in id, description, note, amount, and createdAt from props, but it never includes dispatch in that destructuring list. When you try to call dispatch(removeExpense(id)) in the button's onClick handler, there's no dispatch variable in the component's scope, hence the error.

How connect() works in react-redux v5.0.5

The connect() higher-order component from react-redux v5 does inject the dispatch function into your component's props by default when you don't pass any mapDispatchToProps argument (like you did with connect()(ListItem)). However, this dispatch is only accessible as a property on the component's props—you have to explicitly pull it into your component's scope to use it directly.

Fixing the first code snippet

You just need to add dispatch to your destructured props:

import React from 'react'
import {connect} from 'react-redux'
import {removeExpense} from '../Actions/Actions'

const ListItem = ({id, description, note, amount, createdAt, dispatch})=>(
 <div>
 <h5>{description}</h5>
 <p>Note: {note}</p>
 <p>Amount: {amount}</p>
 <p>Created @{createdAt}</p>
 <button onClick={()=>{dispatch(removeExpense(id))}}>remove</button>
 <br/>
 </div>
)

export default connect()(ListItem);

This way, dispatch is now in the component's scope, and the onClick handler can call it without issue.

Why your second code snippet works

In the second version, you're accessing dispatch directly via props.dispatch—since connect() injected it into the props object, this reference works perfectly. You're not relying on destructuring, so you don't have to explicitly list dispatch to use it.

Is the library version the problem?

No, your versions (Redux v3.7.2, react-redux v5.0.5, React v15) are fully compatible with this pattern. The issue is just a small oversight in how you're accessing the injected dispatch function. In later versions of react-redux (v7+), you might use the useDispatch hook instead of relying on connect() for dispatch, but that's just a newer approach—your original version's behavior is exactly as intended for v5.

内容的提问来源于stack exchange,提问作者Mr. A

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:34:28