redux working

master
Matt Huntington 9 years ago
parent d3645c30a0
commit b623f941bf

@ -3,23 +3,10 @@ import CommentsList from './commentslist.jsx'
import CommentsForm from './commentsform.jsx'
class Comments extends React.Component {
constructor(props){
super(props);
this.state = {
comments: []
}
this.addComment = this.addComment.bind(this);
}
addComment(value){
this.state.comments.push(value); //this alone won't notify React to update the DOM
this.setState({
comments: this.state.comments
});
}
render(){
return <section>
<CommentsList comments={this.state.comments}></CommentsList>
<CommentsForm handleSubmit={this.addComment}></CommentsForm>
<CommentsList></CommentsList>
<CommentsForm></CommentsForm>
</section>
}
}

@ -1,4 +1,5 @@
import React from 'react';
import { connect } from 'react-redux';
class CommentsForm extends React.Component {
constructor(props){
@ -17,4 +18,17 @@ class CommentsForm extends React.Component {
}
}
export default CommentsForm;
const mapDispatchToProps = function(dispatch){
return {
handleSubmit: function(body){
dispatch({type:'ADD', comment: body });
}
}
}
const VisibleCommentsForm = connect(
null,
mapDispatchToProps
)(CommentsForm)
export default VisibleCommentsForm;

@ -1,4 +1,5 @@
import React from 'react';
import { connect } from 'react-redux';
class CommentsList extends React.Component {
render(){
@ -11,4 +12,14 @@ class CommentsList extends React.Component {
}
}
export default CommentsList;
const mapStateToProps = function(state){
return {
comments: state
}
}
const VisibleCommentsList = connect(
mapStateToProps
)(CommentsList);
export default VisibleCommentsList;

@ -1,8 +1,12 @@
import ReactDOM from 'react-dom';
import React from 'react';
import ReactDOM from 'react-dom';
import Comments from './components/comments.jsx';
import { Provider } from 'react-redux';
import store from './store.js';
ReactDOM.render(
<Comments></Comments>,
<Provider store={store}>
<Comments></Comments>
</Provider>,
document.querySelector('main')
);

@ -0,0 +1,14 @@
import { createStore } from 'redux'
let comments = function(state = [], action){
switch(action.type){
case 'ADD':
return [...state, action.comment];
default:
return state
}
}
let store = createStore(comments);
export default store;

@ -4,7 +4,7 @@
"description": "",
"main": "index.js",
"scripts": {
"build": "webpack-dev-server --open"
"build": "webpack-dev-server --open"
},
"author": "",
"license": "ISC",
@ -15,6 +15,8 @@
"babel-preset-react": "^6.24.1",
"react": "^15.5.4",
"react-dom": "^15.5.4",
"react-redux": "^5.0.5",
"redux": "^3.6.0",
"webpack": "^2.5.1",
"webpack-dev-server": "^2.4.5"
}

Loading…
Cancel
Save