React Native Redux-saga get data from action returns patternOrChannel is undefined

jtoj6r0c  于 2023-04-22  发布在  React
关注(0)|答案(3)|浏览(124)

我需要从我的屏幕发送动态数据到action/reducer并从API中获取数据,但是当我在我的rootSaga中屈服时,我会得到这样的错误:
检查时未捕获(patternOrChannel):patternOrChannel未定义
rootSaga在rootSaga
takeEvery
错误:take(patternOrChannel):patternOrChannel未定义
屏幕代码:

import { checkUserLoginStatus, userSignin } from '../actions/user';

class PreCheckout extends PureComponent {
   handleLogin = () => {
     this.props.dispatch(userSignin(username, password));
   };
   render() { .......

行动:

const USER_SIGNIN = 'USER_SIGNIN';

export const userSignin = (username, password) => ({
   type: USER_SIGNIN,
   username,
   password,
});

减速器:

import {
  CHECK_USER_LOGIN_STATUS,
  USER_SIGNIN,
  USER_SIGNIN_RESULT,
  USER_SIGNIN_ERROR,
} from '../actions/user';

const initialState = {
  isLoggedIn: false,
  isFetching: false,
  information: {},
  error: null,
};

const reducer = (state = initialState, action) => {
  switch (action.type) {
    case CHECK_USER_LOGIN_STATUS:
      return {
        ...state,
      };
    case USER_SIGNIN:
      return {
        ...state,
        isFetching: true,
      };
    case USER_SIGNIN_RESULT:
      return {
        ...state,
        isFetching: false,
        information: action.result,
      };
    case USER_SIGNIN_ERROR:
      return {
        ...state,
        isFetching: false,
        error: action.error,
      };

Redux-Saga:

import {
  USER_SIGNIN,
  USER_SIGNIN_RESULT,
  USER_SIGNIN_ERROR,
} from '../actions/user';

function* fetchUserInformation(action) {
  try {
    console.log('fetchUserInformation action: ', action);
    const response = yield call(login, action);
    yield put({
      type: USER_SIGNIN_RESULT,
      result: response.result,
    });
  } catch (e) {
    yield put({
      type: USER_SIGNIN_ERROR,
      error: e.message,
    });
  }
}

export default function* rootSaga() {
  yield takeEvery(USER_SIGNIN, fetchUserInformation);
}
yfjy0ee7

yfjy0ee71#

正如我在注解中提到的,你只是忘记了导出常量。
应该是

export const USER_SIGNIN = 'USER_SIGNIN';

或者

const USER_SIGNIN = 'USER_SIGNIN';

...

export { USER_SIGNIN };

这些类型的bug可以通过启用ruleeslint-plugin-import使用eslint-plugin-import捕获。

nhaq1z21

nhaq1z212#

USER_SIGNIN可能未定义。

jxct1oxe

jxct1oxe3#

如果有人使用TypeScript:当将reducer操作定义为enum时,请确保将每个枚举项的默认值替换为字符串,例如:

// It will fail when using `Action.USER_SIGNIN` 
// because it's implicitly being set as the enum item position index (a number).
enum Action {
  USER_SIGNIN
}

// You need to define as string value instead:
enum Action {
  USER_SIGNIN = 'USER_SIGNIN'
}

相关问题