Redux Saga操作异步操作被调用一次,但是被触发了两次

时间:2020-10-11 01:56:46

标签: react-native redux react-redux redux-saga

因此,我从我的react-native应用程序一次调度了redux-saga操作,它进行了两次API调用。我试图弄清楚为什么会这样,以及如何只让它发送一个。

App.js

  const initFetch = async () => {
    const userToken = await AsyncStorage.getItem("userToken");
    dispatch(fetchLiked({ page: 0, search: "", userToken }));
  };

  useEffect(() => {
    initFetch();
  }, []);

configureStore.js

import { createStore, combineReducers, applyMiddleware } from "redux";
import { persistStore, persistReducer } from "redux-persist";
import AsyncStorage from "@react-native-community/async-storage";
import likedReducer from "./reducers/liked";
import createSagaMiddleware from "redux-saga";
import rootSaga from "./sagas/rootSaga";

const rootReducer = combineReducers({
  liked: likedReducer,
});

const persistConfig = {
  key: "primary",
  storage: AsyncStorage,
};

const persistedReducer = persistReducer(persistConfig, rootReducer);

const sagaMiddleware = createSagaMiddleware();

export default () => {
  let store = createStore(persistedReducer, applyMiddleware(sagaMiddleware));
  sagaMiddleware.run(rootSaga);
  let persistor = persistStore(store);
  return { store, persistor };
};

rootSaga.js

import { take, call, all } from "redux-saga/effects";
import { watchFetchLikedSaga } from "./likedSaga";

export default function* rootSaga() {
  yield all([watchFetchLikedSaga()]);
}

likedSaga.js

import { takeLatest, call, put } from "redux-saga/effects";
import Server from "../../utils/Server";
import { fetchLikedSuccess } from "./../actions/liked";
import { types } from "../actions/types";

function* asyncFetchLiked(data) {
  console.log("sending async fetch");
  const { page, search, userToken } = data.payload;
  try {
    const response = yield call(() =>
      Server.get("/api/titles/getliked", {
        headers: { "auth-token": userToken },
        params: { page: page, search: search },
      })
    );
    yield put(fetchLikedSuccess(response.data));
  } catch (e) {
    console.log(e);
  }
}

export function* watchFetchLikedSaga() {
  yield takeLatest(types.SEND_REQUEST, asyncFetchLiked);
}

export const fetchLiked =(数据)=> { 返回{ 类型:types。SEND_REQUEST, 有效负载:数据, }; };

actions / liked.js

export const fetchLiked = (data) => {
  console.log("fetchLiked");
  return {
    type: types.SEND_REQUEST,
    payload: data,
  };
};

export const fetchLikedSuccess = (data) => {
  console.log("fetchLikedSuccess");
  return {
    type: types.SEND_REQUEST_SUCCESS,
    payload: data,
  };
};

export const fetchLikedFailure = (error) => {
  return {
    type: types.SEND_REQUEST_FAILURE,
    payload: {},
    error: error,
  };
};

我的console.log输出看起来像这样。您可以看到该动作仅被调度了一次,但是它正在发送两个异步请求并两次调用reducer成功动作。

fetchLiked
sending async fetch
sending async fetch
fetchLikedSuccess
fetchLikedSuccess

0 个答案:

没有答案