3.1 KiB
Integrate Redux Into Comments Part 2
The last section works, but there are some optimizations we can make
Lesson Objectives
- Install
react-redux - Map Redux State To The CommentsList Component
- Map a Dispatch ADD Action to a CommentsForm Component property
Install react-redux
npm install react-redux --save-dev
Import react-redux's Provider module in js/index.js:
import { Provider } from 'react-redux';
In js/index.js wrap <Comments></Comments> in a <Provider></Provider> component to make redux available to the Comments component. Also set the store property to the store we import from ./store.js:
import store from './store.js';
ReactDOM.render(
<Provider store={store}>
<Comments></Comments>
</Provider>,
document.querySelector('main')
);
Map Redux State To The CommentsList Component
In js/components/commentslist.jsx, import connect from react-redux:
import { connect } from 'react-redux';
In js/components/commentslist.jsx create a function that will map redux state to component properties:
const mapStateToProps = function(state){
return {
comments: state
}
}
In js/components/commentslist.jsx connect the mapper with the component:
const ConnectedComponent = connect(
mapStateToProps
)(CommentsList);
In js/components/commentslist.jsx, export VisibleCommentsList:
export default ConnectedComponent;
You can now remove the constructor/componentDidMount functions and change this.state.comments.map to this.props.comments.map. We're back to using props instead of component state:
class CommentsList extends React.Component {
render(){
return <ul>
{this.props.comments.map((comment, index) =>
<li key={index}>
{comment.author} says: "{comment.body}"
</li>
)}
</ul>
}
}
Map a Dispatch ADD Action to a CommentsForm Component property
Import connect component from react-redux into js/components/commentsForm.jsx:
import { connect } from 'react-redux';
Now create a function that will map a dispatch to a property in js/components/commentsForm.jsx:
const mapDispatchToProps = function(dispatch){
return {
createComment: function(comment){
dispatch({type:'ADD', comment: comment });
}
}
}
Connect the mapper to the CommentsForm component in js/components/commentsForm.jsx:
const VisibleCommentsForm = connect(
null, //normally the mapStateToProps function
mapDispatchToProps
)(CommentsForm)
Export the VisibleCommentsForm component:
export default VisibleCommentsForm;
Refactor handleSubmit to use the createComment component prop:
handleSubmit(event){
event.preventDefault();
this.props.createComment({
body: this.refs.body.value,
author: this.refs.author.value
});
}