redux 异步请求操作

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值