09.使用react-thunk解决异步action问题

使用方式
import { createStore, applyMiddleware } from 'redux'import thunk from 'redux-thunk'const store = createStore(weight, applyMiddleware(thunk))
export const eatAsync = () =>{ return dispatch =>{ setTimeout(()=>{ // dispatch(eat('煎饼')) dispatch({type: EAT}) },2000) }}
源码
import { createStore } from 'redux'const EAT = 'eat'const HUNGRY = 'hungry'// reducerexport const weight = (state = 160 , action) => { switch (action.type) { case EAT: return state + 10 case HUNGRY: return state - 10 default: return 160 }}// const store = createStore(weight)// actionexport const eat = (data) => { console.log('stark wang 正在吃'+ data) return {type: EAT}}export const hungry = () => { console.log('饿了一天') return {type: HUNGRY}}export const eatAsync = () =>{ return dispatch =>{ setTimeout(()=>{ dispatch(eat('煎饼')) },2000) }}
import React from 'react'import logo from './logo.svg'import './App.css'import { eat, hungry, eatAsync } from './stark.redux'import { connect } from 'react-redux'class App extends React.Component { render () { const {num, eat, hungry , eatAsync} = this.props return ( <div className='App'> <header className='App-header'> <img src={logo} className='App-logo' alt='logo' /> <p> 【redux完全指南】系列1:从入门到会用 <br></br> hi gusy, I am stark </p> <a className='App-link' href='https://shudong.wang' target='_blank' rel='noopener noreferrer'>跟着stark wang 学redux</a> <h2>stark wang 当前的体重为{num}斤</h2> <button onClick={() => {eat()}}> 吃了一坨山珍海味 </button> <button onClick={() => {eatAsync()}}> 等了一会,吃了一个煎饼 </button> <button onClick={() => {hungry()}}> 饿了一天 </button> </header> </div> ) }}// const mapStateToProps = (state)=>{// return {num:state}// }// const actionCreators = {eat,hungry}export default connect((state)=>{ return {num:state}},{eat,hungry,eatAsync})(App)
import React from 'react';import ReactDOM from 'react-dom';import './index.css';import App from './App';import * as serviceWorker from './serviceWorker';import { createStore, applyMiddleware } from 'redux'import { weight } from './stark.redux'import { Provider } from 'react-redux'import thunk from 'redux-thunk'const store = createStore(weight, applyMiddleware(thunk))// const render = () =>{ReactDOM.render( <Provider store={store}> <App /> </Provider>, document.getElementById('root'));// }// render()// store.subscribe(render)// If you want your app to work offline and load faster, you can change// unregister() to register() below. Note this comes with some pitfalls.// Learn more about service workers: https://bit.ly/CRA-PWAserviceWorker.unregister();