React-redux navigation after calling API

僤鯓⒐⒋嵵緔 提交于 2019-12-11 06:26:47

问题


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.



来源:https://stackoverflow.com/questions/48327700/react-redux-navigation-after-calling-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!