为什么我们需要中间件来支持Redux中的异步流?
dispatch
import * as React from 'react';import * as Redux from 'redux';import { Provider, connect } from 'react-redux';const ActionTypes = { STARTED_UPDATING: 'STARTED_UPDATING', UPDATED: 'UPDATED'};class AsyncApi { static getFieldValue() { const promise = new Promise((resolve) => { setTimeout(() => { resolve(Math.floor(Math.random() * 100)); }, 1000); }); return promise; }}class App extends React.Component { render() { return ( <div> <input value={this.props.field}/> <button disabled={this.props.isWaiting} onClick={this.props.update}>Fetch</button> {this.props.isWaiting && <div>Waiting...</div>} </div> ); }}App.propTypes = { dispatch: React.PropTypes.func, field: React.PropTypes.any, isWaiting: React.PropTypes.bool};const reducer = (state = { field: 'No data', isWaiting: false }, action) => { switch (action.type) { case ActionTypes.STARTED_UPDATING: return { ...state, isWaiting: true }; case ActionTypes.UPDATED: return { ...state, isWaiting: false, field: action.payload }; default: return state; }};const store = Redux.createStore(reducer);const ConnectedApp = connect( (state) => { return { ...state }; }, (dispatch) => { return { update: () => { dispatch({ }; }
update
connect
编辑:
动作创建者本身仍然是一个纯函数,但是它返回的thunk函数不需要是,它可以执行我们的异步调用。
相关分类