我已经在'usersaga.js'中定义了以下redux saga中间件功能
import {call, put, takeEvery, takeLatest} from "redux-saga/effects";
import {REQUEST_API_DATA, receiveApiData} from '../store/actions';
import userServiceObject from '../services/user.service';
// Worker Saga function will be fired on USER_FETCH_ACTIONS
export function* getApiData(action){
console.log(action)
try{
// Do Api Call
const data = yield call(userServiceObject.getUsers);
console.log(data.data);
yield put(receiveApiData(data.data));
}
catch(error){
console.log("this is error part and executing");
console.log(error);
}
}
在“ index.js”文件中,我使用“ run”方法在函数getApiData上方运行
import React from 'react';
import ReactDOM from 'react-dom';
import {createStore, combineReducers, applyMiddleware } from 'redux';
import {Provider} from 'react-redux';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import contactReducer from './store/reducers/userlist';
// For Creating Saga and connecting store to saga middleware
import createSagaMiddleware from 'redux-saga';
import {getApiData} from './sagas/usersaga';
const sagaMiddleware = createSagaMiddleware();
const rootReducer = combineReducers({
res: contactReducer
})
const store = createStore(rootReducer, applyMiddleware(sagaMiddleware));
sagaMiddleware.run(getApiData);
ReactDOM.render(<Provider store={store}> <App /> </Provider>, document.getElementById('root'));
serviceWorker.unregister();
它成功地从api获取了数据,并且我成功地处理了由“ receiveApiData”动作生成器函数生成的动作中的数据。
我想在由分派的函数“ requestApiData”生成的操作上调用getApiData函数。操作名称为“ {类型:REQUEST_API_DATA}”
如何在分派的操作上运行getApiData。
我的用户列表reducer文件如下所示
import * as actionTypes from "../actions";
const initialState = {
value: '',
results: []
};
const reducer = (state = initialState, action) => {
switch(action.type){
case actionTypes.STORE_CONTACTS: // This is for storing all contacts in the state here
console.log(action.values)
return {
...state,
results: action.values
}
case actionTypes.RECEIVE_API_DATA:
console.log(action);
return{
...state,
results: action.contacts
}
case actionTypes.DELETE_CONTACT:
return {
...state,
results: action.value
}
case actionTypes.ADD_CONTACT:
// perform add action to the database, update state and return All new data
return {
...state,
}
case actionTypes.EDIT_CONTACT:
return {
...state,
}
default:
return state;
}
};
export default reducer;
答案 0 :(得分:1)
您需要使用实际上已经在usersaga.js中导入的takeEvery
效果
因此,在usersaga.js中添加以下传奇:
export function* requestWatcher(action){
yield takeEvery('REQUEST_API_DATA', getApiData);
}
然后在index.js中运行此传奇,而不是直接运行getApiData
:
sagaMiddleware.run(requestWatcher);
这是redux-saga的基本概念之一,我真的建议您阅读文档https://redux-saga.js.org/docs/basics/UsingSagaHelpers.html