状态组件 => Redux
src
——TodoList.js
import React from 'react';
import TodoItem from './TodoItem';
import store from './store';
class TodoList extends React.Component {
constructor() {
super();
this.state = store.getState();
this.handleDelete = this.handleDelete.bind(this);
this.handleBtnClick = this.handleBtnClick.bind(this);
this.handleInputChange = this.handleInputChange.bind(this);
this.handleStoreChange = this.handleStoreChange.bind(this);
store.subscribe(this.handleStoreChange);
}
handleStoreChange() {
this.setState(store.getState());
}
handleBtnClick() {
// this.setState({
// list: [...this.state.list, this.state.inputValue],
// inputValue: ''
// })
const action = {
type: 'add_todo_item'
}
store.dispatch(action);
}
handleInputChange(e) {
// this.setState({
// inputValue: e.target.value
// })
const action = {
type: 'change_input_value',
value: e.target.value
}
store.dispatch(action);
}
handleDelete(index) {
// const list = [...this.state.list];
// list.splice(index, 1);
// this.setState({
// list: list
// })
const action = {
type: 'delete_todo_item',
value: index
}
store.dispatch(action);
}
getTodoItems() {
const { list } = this.state;
return (
list.map((item, index) => {
return (
<TodoItem
key={index}
index={index}
content={item}
delete={this.handleDelete}
/>
);
})
);
}
render() {
const { inputValue } = this.state;
return (
<div>
<div>
<input value={inputValue} onChange={this.handleInputChange}/>
<button onClick={this.handleBtnClick}>add</button>
</div>
<ul>{this.getTodoItems()}</ul>
</div>
);
}
}
export default TodoList;
src
——store
————index.js
import { createStore } from 'redux';
import reducer from './reducer';
const store = createStore(reducer, window.__REDUX_DEVTOOLS_EXTENSION__ &&window.__REDUX_DEVTOOLS_EXTENSION__());
export default store;
src
——store
————reducer.js
const defaultState = {
list: [],
inputValue: ''
}
export default (state = defaultState, action) => {
if (action.type === 'change_input_value') {
const newState = JSON.parse(JSON.stringify(state));
newState.inputValue = action.value;
return newState;
}
if (action.type === 'add_todo_item') {
const newState = JSON.parse(JSON.stringify(state));
newState.list.push(newState.inputValue);
newState.inputValue = '';
return newState;
}
if (action.type === 'delete_todo_item') {
const newState = JSON.parse(JSON.stringify(state));
newState.list.splice(action.value, 1);
return newState;
}
return state;
}
src
——TodoItem.js
import React from 'react';
class TodoItem extends React.Component {
constructor(){
super();
this.handleDelete = this.handleDelete.bind(this);
}
handleDelete() {
this.props.delete(this.props.index);
}
render() {
return (
<li onClick={this.handleDelete}>{this.props.content}</li>
);
}
}
export default TodoItem;
网友评论