Reputation: 375
Recently I've been using react classes and using mapStateToProps and the react-redux connect, i've been able to use actions within my classes because of this, however now I'm trying to write functions that don't belong to a class like the following
import { some_imported_action } from '../actions/my_actions';
export function f() {
some_imported_action();
}
But I'm having trouble trying to get the function to run the action imported, I assume the problem is trying to use the react-redux connect with a function instead of a class. When I run the code above nothing happens, no errors but the action doesn't execute.
I've tried importing prop-types and making the function required with
some_imported_action: PropTypes.func.isRequired
The errors I get from trying to run it are things to do with either 'this', or 'props' is undefined in the line.
this.props.some_imported_action();
I think it might not even be possible without a class, any ideas? Thanks
Upvotes: 1
Views: 568
Reputation: 4320
When your f()
function is called nothing happens with Redux because the action creator (some_imported_action
) is not connected to your store.
Redux actions needs to be dispatched using the store.dispatch
function in order to be handled by reducers.
The connect function from react-redux receive as second argument a mapDispatchToProps
object or function:
[mapDispatchToProps(dispatch, [ownProps]): dispatchProps]
(Object or Function):If an object is passed, each function inside it is assumed to be a Redux action creator. An object with the same function names, but with every action creator wrapped into a dispatch call so they may be invoked directly, will be merged into the component’s props.
If a function is passed, it will be given dispatch as the first parameter. It’s up to you to return an object that somehow uses dispatch to bind action creators in your own way.
Example passing a callback prop called someAction
binded with store dispatch
:
import { connect } from 'react-redux';
const someAction = () => ({ type: 'SOME_ACTION' });
function MyComponent({ someAction }) {
return <div onClick={someAction}>...</div>;
}
export default connect(null, { someAction })(MyComponent);
Read more info related to React-Redux connect
Upvotes: 2