reduxの非同期

11354 ワード

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;