【问题标题】:Redux-saga runs in a inifinite loopRedux-saga 无限循环运行
【发布时间】:2018-11-10 22:31:04
【问题描述】:

即使在再次触发 PROJECTS_SUCCEDED 之后,Redux saga 仍会无限循环运行,它会运行回 fetchData 方法。请在下面找到传奇代码

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(),
    ]);
}

【问题讨论】:

    标签: redux react-redux redux-saga


    【解决方案1】:

    能够通过将生命周期方法更改为componentWillMount而不是componentDidMount来解决上述问题

    【讨论】:

    【解决方案2】:

    这里需要使用action type来请求

    function* dashboardSaga(){ console.log('saga ran once') yield takeLatest(actions.PROJECTS_REQUESTING, fetchData); }

    【讨论】:

      猜你喜欢
      • 2017-10-15
      • 2017-05-30
      • 2017-09-20
      • 1970-01-01
      • 2017-04-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多