Reputation: 1495
Going through the react-redux docs, I'm trying to understand why the
todo example uses connect
and mapDispatchToProps
vs why the reddit example uses a more traditional render method & passing the dispatch through a handler as props to the child component. Is there a reason for this? I can only guess that it's because the former example has a container component correspond to only one presentational component whereas the latter example's container component contains two presentational components so it would not make sense to use connect (nor is it possible) on two components.
const getVisibleTodos = (todos, filter) => {
...
const mapDispatchToProps = (dispatch) => {
return {
onTodoClick: (id) => {
dispatch(toggleTodo(id))
}
}
}
const VisibleTodoList = connect(
mapStateToProps,
mapDispatchToProps
)(TodoList)
class App extends Component {
...
handleChange(nextReddit) {
this.props.dispatch(selectReddit(nextReddit))
}
...
render() {
...
return (
<div>
<Picker value={selectedReddit}
onChange={this.handleChange}
options={[ 'reactjs', 'frontend' ]} />
<p>
...
Upvotes: 2
Views: 3268
Reputation: 3902
It's perfectly okay to pass dispatch
to your component unless you don't want your component to misuse the dispatch
function and dispatch actions that are not supposed to be dispatched from that component!
If you want to limit your component, you don't want to pass dispatch
directly to the component. You'll want to pass specific action creators through mapDispatchToProps
.
I think it boils down to coding standards, really. If you decide to be strict on your components and not allow them to directly dispatch any action, you can use mapDispatchToProps
to pass only specific action creators.
Bonus: In the first example, you're passing (id) => dispatch(toggleTodo(id))
function to your component. Try using bindActionCreators
from redux instead of manually creating that function! Good luck.
UPDATE
export const dataLoadRequest = () => {
return {
type: 'DATA_LOAD_REQUEST',
}
}
In your Component.js
file, you need to import two things.
import { dataLoadRequest } from 'actions.js';
import { bindActionCreators } from 'redux';
class Component extends React.Component{
...
componentDidMount(){
this.props.actions.dataLoadRequest();
}
...
}
const mapStateToProps = (state) => ({
...
});
const mapDispatchToProps = (dispatch) => ({
actions: bindActionCreators(dataLoadRequest, dispatch)
});
export default connect(
mapStateToProps,
mapDispatchToProps
)(Component);
Upvotes: 4