useDispatch()和useSelector()不会在钩子中反应原生吗?

时间:2020-03-03 07:54:44

标签: react-native redux react-hooks redux-thunk react-functional-component

在React Native中,我从类转移到了钩子,但是在使用带钩子的redux时遇到了一些问题。

到目前为止我的工作

Login.js

const Login = props => {
  const {navigation} = props;
  const dispatch = useDispatch();
  const {success, loading, error} = useSelector(state => state.auth);
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');

  const onLoginPress = async () => {
    await dispatch(login(email, password)); //here VSCode give hints await is useless ? Why ?  how to use await then ?
    if (success) {
      navigation.navigate('Home');
    } else {
      alert(error || 'Invalid Credentials. Please Try again');
    }
  };

//other code


export default Login;

当用户按下登录按钮时,我正在调度登录操作。但是问题是应用卡在这里,动作无法完成,并且始终保持auth_loading

我的登录操作

export const login = (email, pass) => {
  return async dispatch => {
    dispatch(authLoading());
    try {
      const res = await firebaseService
        .auth()
        .signInWithEmailAndPassword(email, pass);   //here app action stucks
      dispatch(loginSuccess(res));
    } catch (err) {
      dispatch(authFailed(err.message));
    }
  };
};

我的减速器

import {
  LOGIN_EMAIL_CHANGED,
  LOGIN_PASS_CHANGED,
  LOGIN_SUCCESS,
  REGISER_SUCCESS,
} from '../types';
import {AUTH_FAILED, AUTH_LOADING} from '../actions/AuthActions';

const initialState = {
  loginEmail: null,
  loginPass: null,
  loading: false,
  success: false,
  user: null,
  error: '',
  authenticated: false,
};

export const AuthReducer = (state = initialState, action) => {
  switch (action.type) {
    case LOGIN_EMAIL_CHANGED:
      return {
        ...state,
        loginEmail: action.payload,
      };
    case LOGIN_PASS_CHANGED:
      return {
        ...state,
        loginPass: action.payload,
      };
    case AUTH_LOADING: {
      return {
        ...state,
        success: false,
        loading: true,
        error: '',
      };
    }
    case AUTH_FAILED: {
      return {
        ...state,
        loading: false,
        success: false,
        error: action.payload,
      };
    }
    case LOGIN_SUCCESS: {
      return {
        ...state,
        user: action.payload,
        loading: false,
        success: true,
        error: null,
      };
    }
    case REGISER_SUCCESS: {
      return {
        ...state,
        user: action.payload,
        loading: false,
        success: true,
        error: null,
      };
    }
    default:
      return state;
  }
};

我使用钩子的方式正确吗?

或者在钩子中分派动作后如何等待。 ?

我们将不胜感激。

谢谢

0 个答案:

没有答案