Reputation:
I am trying to understand the connect function in redux.
I have this:
connect(undefined, (dispatch, { setState }) => ({
...
}))
However, I also want to pass through this:
{ match }: { match: Match }
In a similar fashion, like this:
connect(undefined, (dispatch, { match }: { match: Match }) => ({
...
}))
How would I combine the two? I am looking for something along the lines of this (obviously this doesn't work)
connect(undefined, (dispatch, { setState, { match }: { match: Match } }) => ({
...
}))
This connect function, along with other functions, is wrapped in a compose
Upvotes: 3
Views: 3864
Reputation: 6450
For what it's worth - do not pass around setState
- that's an anti-pattern.
This is the common syntax/construction for connect regarding a component :
import { connect } from 'react-redux'
const TodoItem = ({ todo, destroyTodo }) => {
return (
<div>
{todo.text}
<span onClick={destroyTodo}> x </span>
</div>
)
}
const mapStateToProps = state => {
return {
todo: state.todos[0]
}
}
const mapDispatchToProps = dispatch => {
return {
destroyTodo: () =>
dispatch({
type: 'DESTROY_TODO'
})
}
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(TodoItem)
Per your question, let's break the syntax down a little easier without all of the properties and look at it as simply as possible :
(dispatch) => {
test : (dispatch, setState /* don't do this */) => {
dispatch('do a thing')
}
}
Upvotes: 2
Reputation: 6625
The mapDispatchToProps
is a simple function which returns an object. The object's key is a name of your method and value is your actual function.
Your method should look like this:
const mapDispatchToProps = dispatch => {
return {
fooMethod: () => {},
barMethod: () => {},
};
};
connect(undefined, mapDispatchToProps)(<Your component>);
After that, you can get access to these methods via props
.
Upvotes: 7