Redux异步解决方案 1. Redux-Thunk中间件
    		       		warning:
    		            这篇文章距离上次修改已过432天,其中的内容可能已经有所变动。
    		        
        		                
                Redux-thunk是Redux的一个中间件,它使得action creator可以返回一个函数,而不是一个普通的对象。这个函数会被Redux store在dispatch时调用,而不是被当作普通的action。这样,我们就可以在这个函数内部进行异步操作,比如发送AJAX请求,并根据异步操作的结果来dispatch一个或者多个action。
以下是一个简单的例子:
// 首先,你需要将redux-thunk中间件应用到你的store中
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers';
 
const store = createStore(
  rootReducer,
  applyMiddleware(thunk)
);
 
// 然后,你可以创建一个action creator,它返回一个函数
// 这个函数接收dispatch作为参数,并且可以进行异步操作
 
function fetchData() {
  return function (dispatch) {
    fetch('https://api.example.com/data')
      .then(response => response.json())
      .then(data => dispatch({ type: 'FETCH_SUCCESS', payload: data }))
      .catch(error => dispatch({ type: 'FETCH_ERROR', payload: error }));
  };
}
 
// 当你需要进行异步操作时,你可以dispatch这个action creator
store.dispatch(fetchData());在这个例子中,fetchData是一个action creator,它返回一个函数。这个返回的函数接收store的dispatch方法作为参数,然后通过异步的方式获取数据,并根据获取数据的结果来dispatch不同的action。这样,我们就可以在store中处理异步操作而不会使redux变得复杂。
评论已关闭