即使再次触发PROJECTS_SUCCEDED后,Redux传奇也将无限循环运行,并运行回fetchData方法。请在下面找到saga代码
import axios from 'axios';
import { put, all, take, call, takeLatest , takeEvery} from 'redux-saga/effects';
import actions from './actions';
const getRequest = () =>{
const data = fetch('https://jsonplaceholder.typicode.com/todos/1')
.then( res => res.json())
.catch(err => {throw err});
return data;
}
function* fetchData(action) {
console.log('fetchdata');
try{
const data = yield call(getRequest);
console.log(data)
yield put({type:actions.PROJECTS_SUCCEDED, payload:data});
}
catch (err){
yield put({type:actions.PROJECTS_FAILED,err:err});
}
}
function* dashboardSaga(){
console.log('saga ran once')
yield takeLatest(actions.projectsRequested, fetchData);
}
export default dashboardSaga;
并在componentDidMount中调用该动作
componentDidMount() {
this.props.projectsRequested();
}
并且根传奇是
import { all } from 'redux-saga/effects';
import homeSaga from './dashboard/sagas';
export default function* rootSaga(getState) {
yield all([
homeSaga(),
]);
}
答案 0 :(得分:0)
能够通过将生命周期方法更改为componentWillMount而不是componentDidMount来解决上述问题
答案 1 :(得分:0)
在这里您需要使用操作类型进行请求
function* dashboardSaga(){
console.log('saga ran once')
yield takeLatest(actions.PROJECTS_REQUESTING, fetchData);
}