redux的异步

redux的异步

异步请求一个数据

在actionCreators中请求数据
    
import * as type from './type'

import store from '../index'

const actionCreators = {
    countAdd () {
        let action = {
            type: type.INCREMENT
        }
        store.dispatch(action)
    },
    getName () {
        fetch('/json.json')//使用fetch请求数据
        .then( res => res.json() )
        .then( res =>{
        let action = {//请求成功之后直接创建一个动作
            type: type.GETNAME,
            payload: res//将获取到的数据赋值给payload,再发送到reducer中,再进行数据修改
        }
        store.dispatch(action)//发送动作
        } )
        .catch( err => {if(err) throw err} )
    }
}
export default actionCreators;


视图代码
        
import React from 'react';

import store from '../../store'

import actionCreators from '../../store/counta/actionCreators'

class Count extends React.Component{
    constructor () {
        super()
        this.state = {
            count: store.getState().counta.count,//创建一个状态,只有当前组件的状态改变了,视图才会改变
            name:''
        }
    }
    async componentDidMount () {//重新获取数据,重新赋值给状态
        store.subscribe( ()=>{
            this.setState({
                count: store.getState().counta.count
            })
        } )
        //由于发送请求是异步的,所以执行顺序在修改数据之后,所以修改数据前并没有获取到数据,需要使用async 函数来先发送请求获取数据,然后再重新赋值
        await actionCreators.getName()
        store.subscribe( () => {
            this.setState({
                name:store.getState().counta.mingzi
            })
        })
    }
    
    countadd = () => {//触发actionCreatoes中的方法,然后actionCreators发送到reducer中,reducer改修改数据
        actionCreators.countAdd()
    }
    
    render () {
        let { count } = this.state
        return (
            <div>
                <button onClick = { this.countadd }> 点击加 </button>
                <p> { count } </p>
                <p> name:{ this.state.name } </p>
            </div>
        )
    }
}
export default Count;


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值