classExampleComponentextendsReact.Component{constructor(props){super(props);this.state={name:'',loading:false,errorMessage:''};this._getRandomName=this.getRandomName.bind(this);}render(){const{name,errorMessage}=this.state;return(<div><h1>{name}</h1><buttononClick={this._getRandomName}>PRESSME!</button>{errorMessage&&<div>{errorMessage}</div> }</div>);}getRandomName(){// 重点是这么一段代码this.setState({loading:true})fetch('https://randomuser.me/api/').then(response=>response.json()).then(data=>{constperson=data.results[0];this.setState({name:`${person.name.first}${person.name.last}`,loading:false})}).catch(reason=>{this.setState({errorMessage:'get name failed',loading:false})});}}
classExampleComponentextendsReact.Component{...getRandomName(){this.props.fetchRequest(true)fetch('https://randomuser.me/api/').then(response=>response.json()).then(data=>{constperson=data.results[0];this.props.fetchSuccess(`${person.name.first}${person.name.last}`,false)}).catch(reason=>{this.props.fetchFailure('get name failed',false)});}}
//actions.jsexportfunctionfetchRandmonName(){returnfunction(dispatch){dispatch(fetchRequest(true))returnfetch('https://randomuser.me/api/').then(response=>response.json()).then(data=>{constperson=data.results[0];dispatch(fetchSuccess(`${person.name.first}${person.name.last}`,false))}).catch(reason=>{dispatch(fetchFailure('get name failed',false))})}}constmapDispatchToProps=dispatch=>{return{fetchRandmonName:()=>{dispatch(fetchRandmonName())}}}//ExampleComponent.jsgetRandomName(){this.props.fetchRandmonName();}