鍍金池/ 問答/HTML/ redux-saga 多次觸發(fā)action的問題?

redux-saga 多次觸發(fā)action的問題?

1.rootSaga.js

import { fork, all } from "redux-saga/effects";
// import sub-sagas from submodules
import { assemblyLineSaga } from "@/routes/Devops/AssemblyLine/saga";
import { DashboardSaga } from "@/routes/Devops/Dashboard/saga";


export default function* rootSaga() {
  yield all([...assemblyLineSaga, ...DashboardSaga]);
}

2.dashboard/actions.js

export const GET_ALLDATA_SRART = "GET_ALLDATA_SRART";
export const GET_ALLDATA_SUCCESS = "GET_ALLDATA_SUCCESS";
export const GET_ALLDATA_FAILED = "GET_ALLDATA_FAILED";
export function getAllList(payload) {
 return {
  type: GET_ALLDATA_SUCCESS,
  payload
 };
}

3.dashboard/reducer.js

const initialState = {};
export default (state = initialState, action) => {
  switch (action.type) {
   case Actions.GET_ALLDATA_FAILED:
  return state;
   case Actions.GET_ALLDATA_SUCCESS:
  return {
    ...state,
    ...action.payload
  };
   case Actions.GET_ALLDATA_FAILED:
     return state;
  default:
     return state;
 }
};

4.dashboard/saga.js

import { call, put, fork, takeLatest, takeEvery } from "redux-saga/effects";
import { getList } from "./service";
import * as Actions from "./actions";
function* getAllList() {
try {
 yield put({
  type: Actions.GET_ALLDATA_SRART,
});
const list = yield call(getList);
 yield put({
  type: Actions.GET_ALLDATA_SUCCESS,
  payload: list
 });
} catch (error) {
  yield put({ type: Actions.GET_ALLDATA_FAILED, error });
  }
}
export const DashboardSaga = [fork(getAllList)];

5.dashboard/service.js

import Http from "@/utils/http";
export const getList = () => {
 return Http.get(
  "https://api.github.com/search/repositories?q=javascript&sort=stars"
 );
};

6.dashboard/view.js

import { connect } from "react-redux";
import { getAllList } from "./actions";
...
componentDidMount() {
  this.props.getAllList()
}
export default connect(state => ({ state }), { getAllList })(Dashboard);

發(fā)現(xiàn)調(diào)用action的順序為 dispatch "GET_ALLDATA_SRART" => "GET_ALLDATA_SUCCESS" => "GET_ALLDATA_SUCCESS" 并且第一個 "GET_ALLDATA_SUCCESS" 返回的是payload是undefined.

回答
編輯回答
柒喵

。。亂的不行,

componentDidMount() {
  this.props.getAllList()
}

這個東西你把它去掉你會發(fā)現(xiàn)"GET_ALLDATA_SRART" => "GET_ALLDATA_SUCCESS" 還是會執(zhí)行。

先理一理思路再來寫吧。

(dashboard/actions.js)里getAllList 返回的action應(yīng)該是GET_ALLDATA_SRART, 然后你(dashboard/saga.js)getAllListtry catch里面就不要執(zhí)行GET_ALLDATA_SRART 了,你要做的是用takeLatest 或 takeEvery監(jiān)聽GET_ALLDATA_SRART這個typeaction去執(zhí)行你的getAllList事件


start 不是 srart,還有你沒必要把函數(shù)名都設(shè)置成一樣的把,這么多getAllList看著都暈。

2017年5月29日 19:04