在Redux中,事件分发是通过store.dispatch(action)方法来触发的。Saga是Redux中的中间件,它可以拦截并处理部分或全部的action,同时还可以发起新的action。
下面是一个示例,展示了如何按到达顺序将事件分发到Saga和Redux中:
import { createStore, applyMiddleware } from 'redux';
import createSagaMiddleware from 'redux-saga';
import rootReducer from './reducers';
import rootSaga from './sagas';
const sagaMiddleware = createSagaMiddleware();
const store = createStore(rootReducer, applyMiddleware(sagaMiddleware));
sagaMiddleware.run(rootSaga);
FETCH_DATA
:const fetchData = () => ({
type: 'FETCH_DATA',
});
FETCH_DATA
action,并处理相应的逻辑:import { takeEvery, put } from 'redux-saga/effects';
function* fetchDataSaga() {
try {
// 执行异步操作...
const data = yield call(api.fetchData);
// 成功后,触发另一个action
yield put({ type: 'FETCH_DATA_SUCCESS', payload: data });
} catch (error) {
// 处理错误
yield put({ type: 'FETCH_DATA_FAILURE', error });
}
}
function* rootSaga() {
// 监听FETCH_DATA action,并调用fetchDataSaga处理
yield takeEvery('FETCH_DATA', fetchDataSaga);
}
export default rootSaga;
FETCH_DATA_SUCCESS
和FETCH_DATA_FAILURE
action:const initialState = {
data: null,
error: null,
};
const reducer = (state = initialState, action) => {
switch (action.type) {
case 'FETCH_DATA_SUCCESS':
return {
...state,
data: action.payload,
error: null,
};
case 'FETCH_DATA_FAILURE':
return {
...state,
data: null,
error: action.error,
};
default:
return state;
}
};
export default reducer;
connect
函数将action和state绑定到组件的props上,并触发FETCH_DATA
action:import React, { useEffect } from 'react';
import { connect } from 'react-redux';
import { fetchData } from './actions';
const MyComponent = ({ fetchData, data, error }) => {
useEffect(() => {
fetchData();
}, []);
if (error) {
return Error: {error.message};
}
if (!data) {
return Loading...;
}
return Data: {data};
};
const mapStateToProps = state => ({
data: state.data,
error: state.error,
});
const mapDispatchToProps = {
fetchData,
};
export default connect(mapStateToProps, mapDispatchToProps)(MyComponent);
以上就是一个按到达顺序将事件分发到Saga和Redux的示例。在这个示例中,当组件加载时,它会触发FETCH_DATA
action,然后Saga会拦截该action,并执行异步操作。根据操作的结果,Saga会触发不同的action,然后Redux的reducer会根据这些action来更新状态。最后,更新后的状态会通过mapStateToProps
函数绑定到组件的props上,从而更新组件的显示。