- Learning Redux
- Daniel Bugl
- 315字
- 2025-04-04 18:31:11
ConnectedFilterList component
Next, we implement the ConnectedFilterList component. For this component, we need to use mapDispatchToProps to inject the action creators:
Create a src/containers/ConnectedFilterList.jsx file with the following imports:
import { connect } from 'react-redux' import { bindActionCreators } from 'redux' import FilterList from '../components/FilterList.jsx'
import { setFilter, clearFilter } from '../actions'
Then, we define the mapStateToProps function:
const mapStateToProps = (state, props) => {
This time, we cannot directly return filters from the state; we need to figure out which filters are possible by going through all the posts and adding categories to an array:
const categories = state.posts.reduce((acc, post) => {
We use reduce(fn, init) here, which goes through all the elements in an array, such as map(fn). However, it allows you to have a custom result, which in our case is the acc argument. In the function, we check if acc already contains a category, and if not, add it and return the new acc:
if (!acc.includes(post.category)) { return [ ...acc, post.category ] } return acc
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce.
The second argument to reduce is the initial state, which in our case is an empty array:
}, [])
Now, that we have an array of categories, we can pass it to our FilterList component by returning it from mapStateToProps:
return { categories } }
The next step is defining the mapDispatchToProps function, which injects the setFilter and clearFilter action creators:
const mapDispatchToProps = (dispatch, props) => { return { setFilter: (category) => dispatch(setFilter(category)), clearFilter: () => dispatch(clearFilter()), } }
To shorten that code, we can use the bindActionCreators helper function we imported from Redux earlier:
const mapDispatchToProps = (dispatch, props) => bindActionCreators({ setFilter, clearFilter }, dispatch)
Finally, we call connect() and export the container component:
const ConnectedFilterList = connect(mapStateToProps, mapDispatchToProps)(FilterList) export default ConnectedFilterList