用redux的方式来实现ToDoList
ToDoList.js
import React, { Component } from 'react';
import 'antd/dist/antd.css'
import {Input,Button,List } from 'antd'
import store from './store/store'
// const data=[
// '跑跑卡丁车',
// '穿越火线',
// '真三国无双'
// ]
class ToDoList extends Component {
constructor(props) {
super(props);
this.state = store.getState();
this.storeChange = this.storeChange.bind(this);
store.subscribe(this.storeChange) //订阅Redux的状态
}
render() {
return (
<div>
<Input
placeholder={this.state.inputValue}
style={{width:'250px'}}
onChange={this.inputChangeValue.bind(this)}
/>
<Button type="primary" onClick={this.btnClick.bind(this)}>添加游戏</Button>
<List
bordered
dataSource={this.state.List}
renderItem={(item,index) => (
<List.Item onClick={this.deleteItem.bind(this,index)}>{item}</List.Item>
)}
/>
</div>
)
}
inputChangeValue(e){
const action={
type:'changeInput',
value:e.target.value
}
store.dispatch(action)
}
storeChange(){
this.setState(store.getState)
}
btnClick(){
const action={
type:'addItem'
}
store.dispatch(action)
}
deleteItem(index){
const action={
type:'deleteItem',
value:index
}
store.dispatch(action)
}
}
export default ToDoList;
store.js
import {createStore} from 'redux'
import reducer from './reducer'
const store = createStore(reducer);
export default store;
reducer.js
const defaultState = {
inputValue : 'Write Something',
List:[
'跑跑卡丁车',
'穿越火线',
'真三国无双'
]
}
export default (state = defaultState,action)=>{
console.log(state,action)
if(action.type === 'changeInput'){
let newState = JSON.parse(JSON.stringify(state)) //深度拷贝state
newState.inputValue = action.value
return newState
}
if(action.type === 'addItem'){
let newState = JSON.parse(JSON.stringify(state))
console.log(newState.inputValue)
newState.List.push(newState.inputValue)
return newState
}
if(action.type === 'deleteItem'){
let newState = JSON.parse(JSON.stringify(state))
newState.List.splice(action.value,1)
return newState
}
return state
}