React-Redux中connect传action creators后props无dispatch的原因咨询
dispatch available in props when passing action creators to connect? Great question! Let's break down why this happens and how you can get dispatch back if you need it.
The Default Behavior of connect
When you only pass mapStateToProps to connect (your Case 1), Redux automatically injects the dispatch function as a prop into your component. It assumes you might need to dispatch actions directly in some cases.
But when you pass a second argument to connect—whether it's an object of action creators (like your Case 2 with { setData }) or a mapDispatchToProps function—Redux changes this behavior:
- If you pass an object of action creators,
connectautomatically wraps each creator withdispatchfor you. So callingthis.props.setData()is exactly the same as callingdispatch(setData()). - Since these wrapped action creators handle dispatching for you, Redux doesn't automatically include the raw
dispatchfunction in props by default—it assumes you don't need it anymore.
How to Get dispatch Back in Case 2
If you still need access to the raw dispatch function alongside your wrapped action creators, you have two main options:
Option 1: Use a mapDispatchToProps function instead of an object
Instead of passing the action creators directly as an object, define a mapDispatchToProps function that returns both your wrapped action creators and the dispatch function:
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { setData } from './actions' class App extends Component { render() { console.log('this.props', this.props); // Now includes both setData and dispatch return ( <div className="App"> App </div> ); } } const mapStateToProps = (state) => { return state; }; const mapDispatchToProps = (dispatch) => { return { setData: () => dispatch(setData()), // Wrap the action creator dispatch // Explicitly include dispatch in props }; }; export default connect(mapStateToProps, mapDispatchToProps)(App);
Option 2: (For Function Components) Use the useDispatch Hook
If you refactor your class component to a function component, you can use Redux's useDispatch hook to get access to dispatch directly, without relying on props:
import React from 'react'; import { useSelector, useDispatch } from 'react-redux'; import { setData } from './actions'; function App() { const state = useSelector(state => state); const dispatch = useDispatch(); console.log('dispatch', dispatch); console.log('state', state); return ( <div className="App"> App </div> ); } export default App;
Why This Design Makes Sense
Redux's default behavior here is intentional: when you pass action creators to connect, it's optimizing by giving you pre-wrapped functions that handle dispatching. This reduces boilerplate (you don't have to write dispatch(setData()) every time) and keeps your props cleaner by only including what it thinks you need.
内容的提问来源于stack exchange,提问作者Ravi Malviya

