import React, { Component } from 'react'
import './App.css'
import ListItem from './DelItem'
import store from './store'
import {inputChange, addTo, delItem, initList} from './actions'
import axios from 'axios'
class A extends Component {
constructor (props) {
super(props)
this.state = store.getState()
this.add = this.add.bind(this)
this.inputChange = this.inputChange.bind(this)
this.listen = this.listen.bind(this)
store.subscribe(this.listen)
}
componentDidMount () {
axios.post('queryBannerList', {
type: 1
}).then(res => {
let list = res.data.result.list
store.dispatch(initList(list))
})
}
listen () {
this.setState(store.getState())
}
add () {
store.dispatch(addTo(this.state.inputVal))
store.dispatch(inputChange(' '))
}
inputChange (e) {
let val = e.target.value
store.dispatch(inputChange(val))
}
delItem (i) {
store.dispatch(delItem(i))
}
render () {
const { todos,inputVal } = this.state
return (
<div className='box'>
<div>
<input onChange={this.inputChange} value={inputVal}/>
<button onClick={this.add}>添加</button>
</div>
{
todos.map((todo,i) => (<ListItem key={todo.id} {...todo} delItem={() =>this.delItem(i)}></ListItem>))
}
</div>
)
}
}
export default A
export const initList = lists => {
return {
type: 'INIT_LIST',
lists
}
}
const todos = (state=[], action) => {
switch(action.type) {
case 'ADD_TODO':
return [
...state,
{
text: action.text,
id: action.id,
completed: false
}
]
case 'TOOGLE_TODO':
return state.map(todo =>
(todo.id === action.id) ? {...todo, completed: !todo.completed}:todo
)
case 'DEL_ITEM':
let todos = state
todos.splice(action.index, 1)
return todos
case 'INIT_LIST':
let lists = []
action.lists.forEach(item => lists.push({
text: item.id,
id: item.id,
completed: false
}))
return lists
default:
return state
}
}
export default todos