Функция вызова Redux Saga (выборка ...) не возвращает ничего в реакции на натив - PullRequest
0 голосов
/ 23 января 2020

Я новичок в Redux-Saga, знаю Redux. Я создаю процесс входа в систему с использованием React Native и Redux, Redux-Saga. Это мой первый проект redux-saga, и я не могу получить ответ от функции вызова саги.

Он просто не запущен код после yield call(UserService.loginUserApi, params); ниже - это код.

LoginContainer. js

import React from 'react'
import { Platform, Text, View, Button, ActivityIndicator, Image } from 'react-native'
import { connect } from 'react-redux'
import { ApplicationStyles, Helpers, Images, Metrics } from 'App/Theme'
import LoginActions from 'App/Actions/LoginAction'

class LoginContainer extends React.Component {
    componentDidMount() {
    }

    render() {
        return (
            <View
                style={[
                    Helpers.fill,
                    Helpers.rowMain,
                    Metrics.mediumHorizontalMargin,
                    Metrics.mediumVerticalMargin,
                ]}
            >
                {this.props.isLoading ? (
                    <View>
                        <ActivityIndicator size="large" color="#0000ff" />
                        <Text>{JSON.stringify(this.props.isLoading)}</Text>
                    </View>
                ) : (
                        <View>

                            <Text >To get started, edit App.js </Text>
                            {this.props.loginError ? (
                                <Text >{JSON.stringify(this.props.loginError)}</Text>
                            ) : <Text >{JSON.stringify(this.props.userDetails)}</Text>}
                            <Button
                                onPress={() => this.props.loginUser({
                                    "email": "eve.holt@reqres.in",
                                    "password": "cityslicka"
                                })}
                                title="Refresh"
                            />
                        </View>
                    )}
            </View>
        )
    }

}


const mapStateToProps = (state) => {
    return ({
        userDetails: state.login.userDetails,
        isLoading: state.login.isLoading,
        loginError: state.login.loginError,
    })
};

const mapDispatchToProps = (dispatch) => ({
    loginUser: (payload) => dispatch(LoginActions.loginUser(payload)),
})

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(LoginContainer)

LoginAction . js



const { Types, Creators } = createActions({
    // Fetch user informations
    loginUser: ['params'],
    // The operation has started and is loading
    loginLoading: ['value'],
    // User informations were successfully fetched
    loginUserSuccess: ['user'],
    // An error occurred
    loginUserError: ['errorMessage'],
})

export const LoginTypes = Types
export default Creators

LoginSaga. js

import { put, call, take } from 'redux-saga/effects'
import LoginActions, { LoginTypes } from 'App/Actions/LoginAction'
import { UserService } from 'App/Services/UserService'


export function* getLogin() {
    // while (true) {
    // console.log(LoginActions.loginUser());
    const action = yield take(LoginTypes.LOGIN_USER);
    const { params } = action;
    console.log("params", params);
    // yield put(LoginActions.loginLoading(true))
    let response1 = yield call(UserService.loginUserApi, params);
    console.log("it doesnot print anything", response1);
    // LoginActions.loginUserError('test');
    // console.log("RUN RUn");
    // if (response1) {
    //     console.log("USER", response1);
    //     yield put(LoginActions.loginUserSuccess(response1))
    // } else {
    //     yield put(
    //         LoginActions.loginUserError('There was an error while fetching user informations.')
    //     )
    // }
    // }
}

Sagas / index. js

import { getLogin } from './LoginSaga'
import { LoginTypes } from 'App/Actions/LoginAction'
export default function* root() {
  yield all([
    takeLatest(LoginTypes.LOGIN_USER, getLogin),
  ])
}

LoginReducers. js

import { createReducer } from 'reduxsauce'
import { LoginTypes } from 'App/Actions/LoginAction'

const INITIAL_STATE = {
    userDetails: {},
    isLoading: false,
    loginError: null,
}

export const loginUserError = (state, { errorMessage }) => {
    alert();
    console.log(errorMessage);
    return ({
        ...state,
        userDetails: {},
        isLoading: false,
        loginError: errorMessage,
    })
}

export const loginUserSuccess = (state, { user }) => ({
    ...state,
    userDetails: user,
    isLoading: false,
    loginError: null,
})

export const loginLoading = (state, { value }) => ({
    ...state,
    userDetails: {},
    isLoading: value,
    loginError: null,
})

export const loginReducer = createReducer(INITIAL_STATE, {
    [LoginTypes.LOGIN_USER_SUCCESS]: loginUserSuccess,
    [LoginTypes.LOGIN_USER_ERROR]: loginUserError,
    [LoginTypes.LOGIN_LOADING]: loginLoading,
})

Store / index. js

import configureStore from './CreateStore'
import rootSaga from 'App/Sagas'
import { loginReducer } from 'App/Reducers/LoginReducers'

export default () => {
  const rootReducer = combineReducers({
    login: loginReducer,
  })

  return configureStore(rootReducer, rootSaga)
}

ConfigureStore. js

import { applyMiddleware, compose, createStore } from 'redux'
import createSagaMiddleware from 'redux-saga'
import { persistReducer, persistStore } from 'redux-persist'

/**
 * This import defaults to localStorage for web and AsyncStorage for react-native.
 *
 * Keep in mind this storage *is not secure*. Do not use it to store sensitive information
 * (like API tokens, private and sensitive data, etc.).
 *
 * If you need to store sensitive information, use redux-persist-sensitive-storage.
 * @see https://github.com/CodingZeal/redux-persist-sensitive-storage
 */
import storage from 'redux-persist/lib/storage'

const persistConfig = {
  key: 'root',
  storage: storage,
  /**
   * Blacklist state that we do not need/want to persist
   */
  blacklist: [
    // 'auth',
  ],
}

export default (rootReducer, rootSaga) => {
  const middleware = []
  const enhancers = []

  // Connect the sagas to the redux store
  const sagaMiddleware = createSagaMiddleware()
  middleware.push(sagaMiddleware)

  enhancers.push(applyMiddleware(...middleware))

  // Redux persist
  const persistedReducer = persistReducer(persistConfig, rootReducer)

  const store = createStore(persistedReducer, compose(...enhancers))
  const persistor = persistStore(store)

  // Kick off the root saga
  sagaMiddleware.run(rootSaga)

  return { store, persistor }
}

userServices. js

import { Config } from 'App/Config'
import { is, curryN, gte } from 'ramda'


loginUserApi = (userdetails) => {
  console.log("IN loginUserApi ", userdetails);

  return fetch(Config.API_URL + 'login', {
    method: 'POST',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      email: userdetails.email,
      password: userdetails.password,
    })
  });
  // let data = await response.json();
  // console.log(data);
  // return data;

}

export const UserService = {
  loginUserApi,
}

1 Ответ

0 голосов
/ 25 февраля 2020

Может быть, этот вызов выдает ошибку,

 let response1 = yield call(UserService.loginUserApi, params);

попытайтесь обернуть его в блок "try / catch", возможно, вам придется обработать ошибку

...