The original text is here:How to Export a Connected Component
Depending on your export, you can get a perfectly functional React-Redux connected component, or a component that ignores Redux entirely
In other words, there are two very different worlds:
class Thing extends Component {... }export default connect(mapStateToProps)(Thing);
Copy the code
And this:
export class Thing extends Component {... } connect(mapStateToProps, mapDispatchToProps)(Thing);Copy the code
If you set it to the second instance, you’ll notice all the React stuff, but the Redux functions,mapStateToProps and mapDispatchToProps, do not return
connect
No changes are made to the component
When you wrap a component with connect, for example connect(…) (Thing), it is important to understand that although a connected component is returned, it does not touch the original Thing component at all.
In other words, run connect(…) (Thing), no “connect” to Thing component, missing no. What you do is translate a new component that is wired.
Exporting Connected Components
Therefore, when exporting components, it is important to define which component is connected. Make sure the export keyword appears before the connect call like this:
export defaultconnect(...) (Thing);Copy the code
Why not export both the original component and the wired component?
Exporting both connected and disconnected components is very effective. Great for testing – for example, if you want to test for components that are not connected to the mock Redux Store.
Here is the code to export both unconnected and connected components:
export class Thing extends React.Component {
render() {
return "whatever"; }}const mapState = state= > ({ someValue });
const mapDispatch = { action1, action2 };
export default connect(mapState, mapDispatch)(Thing);
Copy the code
Note that there are two imports, one of which is the name and the other is default. The definition here is important because it affects subsequent imports.
Import wired components
As a general rule, if code uses exprot default, import without {},; Such as:
// Thing.js
export defaultconnect(...) (Thing);// UserOfThing.js
import Thing from './Thing';
Copy the code
If you export a name, use {}:
// Thing.js
export function Thing() {... }// UserOfThing.js
import { Thing } from './Thing';
Copy the code