[由于使用redux-thunk的异步api调用引起的redux道具更改时未触发UseEffect

问题描述 投票:0回答:1

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

问题是,我知道登录成功,这应该触发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;

在减速器中,我看到成功动作实际上是通过检查console.log()触发的。同样在redux开发工具中,我实际上可以看到登录成功并且isLoading属性已更改:enter image description here

reactjs redux react-redux redux-thunk
1个回答
0
投票

这解决了我的问题

const mapStateToProps = (state) => ({
  user: state.userReducer.user,
  isLoading: state.userReducer.isLoading
});
© www.soinside.com 2019 - 2024. All rights reserved.