原先的TodoList.js文件中既包含了UI部分,也包含了业务逻辑操作。为了减小耦合度和提高开发效率,我们一般将UI和业务逻辑拆分开来。
将TodoList中的UI部分转移到一个新的文件TodoListUI.js中:
import React, { Component } from 'react';
import { Input, Button, List } from 'antd';
class TodoListUI extends Component {
render() {
return (
<div style={{ margin: '10px' }}>
<div>
<Input
placeholder={this.props.inputValue}
style={{ width: '250px', marginRight: '10px' }}
onChange={this.props.changeInputValue}
value={this.props.inputValue}
/>
<Button
type="primary"
onClick={this.props.clickBtn}
>
增加
</Button>
</div>
<div style={{ margin: '10px', width: '300px' }}>
<List
bordered
dataSource={this.props.list}
renderItem={(item, index) => (
<List.Item
onClick={() => {
this.props.deleteItem(index)
}
}>
{item}
</List.Item>
)}
/>
</div>
</div>
);
}
}
export default TodoListUI;
在TodoList.js中引入TodoListUI:
import React, { Component } from 'react';
import 'antd/dist/antd.css';
import TodoListUI from './TodoListUI';
import store from './store'; //'./store/index.js'
import {changeInputAction,addItemAction,deleteItemAction} from './store/actionCreaters';
class TodoList extends Component {
constructor(props){
super(props);
this.state = store.getState();
this.changeInputValue = this.changeInputValue.bind(this);
this.storeChange = this.storeChange.bind(this);
this.clickBtn = this.clickBtn.bind(this);
this.deleteItem = this.deleteItem.bind(this);
store.subscribe(this.storeChange);//订阅,同步更新
}
render() {
return (
<TodoListUI
inputValue={this.state.inputValue}
changeInputValue={this.changeInputValue}
clickBtn={this.clickBtn}
list={this.state.list}
deleteItem={this.deleteItem}
/>
);
}
changeInputValue(e){
const action = changeInputAction(e.target.value);
store.dispatch(action);
}
storeChange(){
this.setState(store.getState);
}
clickBtn(){
const action = addItemAction();
store.dispatch(action);
}
deleteItem(index){
const action = deleteItemAction(index);
store.dispatch(action);
}
}
export default TodoList;