Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
React Redux 사용 예
/* 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
You can’t perform that action at this time.