React-redux navigation after calling API

2019-08-04 07:05发布

问题:

Below is my reducer code.

import * as Helper from '../utils/helper';
import AppNavigator from "../Navigation/navigationStack";

const initialState = { user: "" };

export function pedagogyReducer(state = initialState, action){
  switch (action.type) {
    case 'REGISTER':{
      state = {
        ...state,
        user: action.newUser,
        showError: action.showError ? action.showError : false,
        errorMessage: action.errorMessage ? action.errorMessage: "",
      }
      console.log(action.showError);
      {
        ////////here I want to redirect to login if response if success else want to show error message
      }
      if(!action.showError){
        AppNavigator.router.getStateForAction(
          AppNavigator.router.getActionForPathAndParams("Login")
        );
        return state;
      } else {
        return state;
      }
      break;
    }
    default:
    return state;
  }
}

export default pedagogyReducer;

I am not sure should I redirect to success/error screen from reducer or from other file. I have used reducer, action, middleware(fetch APIs) and react-navigation.

回答1:

Reducers should be pure functions, so this isn't the best place for you to put your redirect logic.

A great library that helps dealing with side-effects based on Redux actions is redux-saga, you should take a look at their docs.

Quoting their website:

redux-saga is a library that aims to make application side effects (i.e. asynchronous things like data fetching and impure things like accessing the browser cache) easier to manage, more efficient to execute, simple to test, and better at handling failures.