当使用redux-thunk的异步api调用导致redux道具更改时,不会触发UseEffect

时间:2020-02-18 17:57:56

标签: reactjs redux react-redux redux-thunk

我有一个与redux连接的功能性登录页面,我触发了一个异步事件onSubmit,它将触发emailLogin操作,我正在使用useEffect检测{{1}的更改} prop,以查看登录是否完成。如果登录成功,则redux存储区应具有用户对象,如果登录失败,则用户应保持null。

问题是,我知道登录成功,应该触发isLoading的更改,该更改决定了isLoading的参数,但是useEffect未被触发。此外,从不触发行useEffect之后的console.log('done');。出了点问题。

await emailLogin(authData);

我的动作文件:

import React, { useState, useEffect } from 'react';
import { connect } from 'react-redux';
import { Link, useHistory } from 'react-router-dom';
import { emailLogin } from '../actions/index';

function Login({ user, isLoading, emailLogin }) {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const history = useHistory();

  useEffect(() => {
    console.log('useEffect fired', user, isLoading); //<-----This does not fire after login success
    if (user) {
      history.push('/protected_home');
    } 
  }, [isLoading]);

  const submitEmailLoginForm = async (e) => {
    e.preventDefault();
    const authData = { email, password };
    await emailLogin(authData);
    console.log('done'); // <------- This is never fired
  };

  return (
    <div>
      <h2>Login</h2>
      <Link to="/">back</Link>
      <form onSubmit={submitEmailLoginForm}>
        <label>
          email:
          <input
            type="text"
            name="email"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
          />
        </label>
        <label>
          password:
          <input
            type="text"
            name="password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
          />
        </label>
        <input type="submit" value="Submit" />
      </form>
    </div>
  );
}

const mapStateToProps = (state) => ({
  user: state.user,
  isLoading: state.isLoading
});

const mapDispatch = {
  emailLogin: emailLogin
};

export default connect(mapStateToProps, mapDispatch)(Login);

我的减速机:

import axios from 'axios';

export const authActions = {
  EMAIL_LOGIN_START: '@@EMAIL_LOGIN_START',
  EMAIL_LOGIN_SUCCESS: '@@EMAIL_LOGIN_SUCCESS'
};

export const emailLogin = ({ email, password }) => async (dispatch) => {
  dispatch({ type: authActions.EMAIL_LOGIN_START });
  try {
    const response = await axios.post('http://localhost:5001/api/auth', {
      email: email,
      password: password
    });
    dispatch({
      type: authActions.EMAIL_LOGIN_SUCCESS,
      payload: {
        user: { ...response.data }
      }
    });
  } catch (error) {
    console.log('Should dispatch api error', error.response);
  }
};

在减速器中,我看到成功操作实际上是通过检查import { authActions } from '../actions/index'; const initialState = { user: null, isLoading: false }; const userReducer = (state = initialState, action) => { switch (action.type) { case authActions.EMAIL_LOGIN_START: return { ...state, isLoading: true }; case authActions.EMAIL_LOGIN_SUCCESS: console.log('Reducer check => Login is success'); //<-----this line is printed return { ...state, user: action.payload.user, isLoading: false }; default: return state; } }; export default userReducer; 触发的。同样在redux开发工具中,我实际上可以看到登录成功并且console.log()道具已经改变: enter image description here

1 个答案:

答案 0 :(得分:1)

这解决了我的问题

const mapStateToProps = (state) => ({
  user: state.userReducer.user,
  isLoading: state.userReducer.isLoading
});