Using redux in React class components requires using connect()
function from react-redux
package.
Example:
import React from 'react';
import { connect} from 'react-redux';
import { increment, rate } from '../actions';
class Product extends React.Component {
// ...
}
const mapStateToProps = state => ({
likes: state.likes,
rate: state.rate
})
const mapDispatchToProps = dispatch => ({
increment: () => dispatch(increment()),
rate: (value) => dispatch(rate(value))
});
export default connect(mapStateToProps, mapDispatchToProps)(Product)
react-reduxify
can make this a little simpler.
import reduxify from 'react-reduxify';
...
export default reduxify(Product, 'likes,rate', { increment, rate })
There's no need to write mapStateToProps and mapDispatchToProps.
reduxify
signature:
function reduxify(component, neededStates, neededActions, mergeOptions, options) {
...
}
Parameters
-
component
: React class component to be reduxified (use some states in redux store in that) -
neededStates
(string, array -of string | object- or object): needed state items from redux store. -
neededActions
(object): needed actions. -
mergeOptions
(function): similar tomergeOptions
inconnect()
. -
options
(object): similar tooptions
inconnect()
.
String is the simplest form of using neededStates
. It could be a comma separated list of items with the following format:
{name?:}{state_key}{=default_value?}
name and default_value are optional.
Example:
export default reduxify(Product, 'count,lang:config.lang=EN,year:config.current_year=2020')
This is similar to:
const mapStateToProps = state => {
const props = {
count: state.count,
lang: state.config.lang,
year: state.config.current_year
}
if (typeof props.lang == 'undefined') {
props.lang = 'EN'
}
if (typeof props.year == 'undefined') {
props.year = '2020'
}
return props;
}
export default connect(mapStateToProps, null)(Product)
More examples at: react-reduxify
reduxify
has its own cons though. For example it's not possible to use expressions in the neededStates, while this is possible when writing a manual mapStateToProps
function where you have full control over the state
.
Comments and suggestions are welcomed.
Top comments (0)