简体   繁体   中英

Redux connect passes an unnecessary prop "dispatch" to a connected component

I'm connecting store to the Image component using redux connect. I only expect to retrieve there (in the Image component) one prop from Redux: "images". But I also get an additional prop: "dispatch".

import { connect } from "react-redux";
import Image from "./Image";
import { imagesSelector } from "units/images/selectors";

const mapStateToProps: MapStateToPropsParam = (state) => ({
  images: imagesSelector(state),
});

export default connect(mapStateToProps)(Image);

In the Image component I get: { images: [...], dispatch: function(){...}}

The question: How to exclude dispatch from being passed to my component?

From the react-redux docs:

If you don't specify a second argument to connect() , your component will receive dispatch as a prop by default.

If you don't want this behavior, you can instead pass a second argument to the connect function, which would be the mapDispatchToProps argument.

It can be either a function or an object.

We recommend always using the “object shorthand” form of mapDispatchToProps, unless you have a specific reason to customize the dispatching behavior.

Note that:

  • Each field of the mapDispatchToProps object is assumed to be an action creator
  • Your component will no longer receive dispatch as a prop

Docs: https://react-redux.js.org/using-react-redux/connect-mapdispatch

export default connect(mapStateToProps, null)(Image);

添加 null 作为第二个参数,你就可以开始了

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM