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' )
. then ( res => res. json ( ) )
. then ( res => {
let action = {
type: type. GETNAME ,
payload: res
}
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
} )
} )
await actionCreators. getName ( )
store. subscribe ( ( ) => {
this . setState ( {
name: store. getState ( ) . counta. mingzi
} )
} )
}
countadd = ( ) => {
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;