Created
May 20, 2017 08:17
-
-
Save oiehot/4ab725d00cdb874840cdd66797778aa2 to your computer and use it in GitHub Desktop.
React Redux 사용 예
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* components/Todo.jsx */ | |
import React from 'react' | |
import { connect } from 'react-redux' | |
import * as TodoAction from '../actions/todos' | |
class Todo extends React.Component { | |
render() { | |
return ( | |
<div> | |
<div>{ this.props.text }</div> | |
{ this.props.completed ? <div>DONE</div> : <div>X</div> } | |
<button type="button" onClick={ this.props.onDone }>Done</button> | |
</div> | |
); | |
} | |
} | |
// ---- | |
let mapStoreToProps = (store, ownProps) => { | |
return { | |
text: store.todos[ownProps.index].text, | |
completed: store.todos[ownProps.index].completed | |
} | |
} | |
let mapDispatchToProps = (dispatch, ownProps) => { | |
return { | |
onDone: () => dispatch(TodoAction.completeTodo(ownProps.index)) | |
} | |
} | |
Todo = connect(mapStoreToProps, mapDispatchToProps)(Todo) | |
export default Todo | |
/* components/TodoList.jsx */ | |
import React from 'react' | |
import { connect } from 'react-redux' | |
import Todo from '../components/Todo' | |
import * as TodoAction from '../actions/todos' | |
class TodoList extends React.Component { | |
constructor(props) { | |
super(props) | |
this.state = { | |
text: "" | |
} | |
} | |
onChange = (e) => { | |
this.setState( | |
{text: e.target.value} | |
) | |
} | |
addTodo = (e) => { | |
this.props.onAdd(this.state.text) | |
} | |
render() { | |
const listItems = this.props.todos.map((todo, index) => { | |
return <Todo key={index} index={index} /> | |
}) | |
return ( | |
<div> | |
<div> | |
<input type="text" value={this.state.text} onChange={this.onChange}></input> | |
<button type="button" onClick={this.addTodo}>Add</button> | |
</div> | |
<div> | |
{ listItems } | |
</div> | |
</div> | |
); | |
} | |
} | |
// ---- | |
let mapStoreToProps = (store) => { | |
return { | |
todos: store.todos | |
} | |
} | |
let mapDispatchToProps = (dispatch, ownProps) => { | |
return { | |
onAdd: (text) => dispatch(TodoAction.addTodo(text)) | |
} | |
} | |
TodoList = connect(mapStoreToProps, mapDispatchToProps)(TodoList) | |
export default TodoList |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment