猿问

登录后响应重定向(调度)

在此类项目中成功登录后如何将我的网站重定向到主页:

https://github.com/bradtraversy/mern_shopping_list

操作 ts 文件 [actions/authActions.ts]:

import axios from 'axios';

import { returnErrors } from './errorActions';

import {

  USER_LOADED,

  USER_LOADING,

  AUTH_ERROR,

  LOGIN_SUCCESS,

  LOGIN_FAIL,

  LOGOUT_SUCCESS,

  REGISTER_SUCCESS,

  REGISTER_FAIL

} from './types';

import { IAuthFunction, IConfigHeaders } from '../../types/interfaces';

import { useHistory } from 'react-router-dom';


//


// Register User

export const register = ({ name, email, password }: IAuthFunction) => (

  dispatch: Function

) => {

  // Headers

  const config = {

    headers: {

      'Content-Type': 'application/json'

    }

  };


  // Request body

  const body = JSON.stringify({ name, email, password });


  axios

    .post('/api/auth/register', body, config)

    .then(res =>

      dispatch({

        type: REGISTER_SUCCESS,

        payload: res.data

      })

    )

    .catch(err => {

      dispatch(

        returnErrors(err.response.data, err.response.status, 'REGISTER_FAIL')

      );

      dispatch({

        type: REGISTER_FAIL

      });

    });

};


// Login User

export const login = ({ email, password }: IAuthFunction) => (

  dispatch: Function

) => { 

  // Headers

  const config = {

    headers: {

      'Content-Type': 'application/json'

    }

  };


  // Request body

  const body = JSON.stringify({ email, password });


  const history = useHistory();// <---------- ERROR HERE


  axios

    .post('/api/auth/login', body, config)

    .then(res => {

        dispatch({

          type: LOGIN_SUCCESS,

          payload: res.data

        });

        // const history = useHistory(); <----- tried placing it here too

        // history.push("/dd");

      }

    )

    .catch(err => {

      dispatch(

        console.log(err)

        // returnErrors(err.response.data, err.response.status, 'LOGIN_FAIL')

      );

      dispatch({

        type: LOGIN_FAIL

      });

    });

};

catch 错误返回“错误:无效的钩子调用。钩子只能在函数组件的主体内部调用...”


宝慕林4294392
浏览 106回答 1
1回答

POPMUISE

UseEffect()像这样使用:import { useHistory } from 'react-router-dom';//const LoginForm = ({&nbsp; &nbsp; isAuthenticated,&nbsp; &nbsp; redirectTo, // <-- here&nbsp; &nbsp; error,&nbsp; &nbsp; login,&nbsp; &nbsp; clearErrors}: ILoginForm) => {&nbsp; &nbsp; const history = useHistory();&nbsp; &nbsp; //&nbsp; &nbsp; useEffect(() => {&nbsp; &nbsp; &nbsp; if(redirectTo)&nbsp; &nbsp; &nbsp; &nbsp; history.push(redirectTo);&nbsp; &nbsp; });}const mapStateToProps = (state: IAuthReduxProps) => ({&nbsp; &nbsp; isAuthenticated: state.auth.isAuthenticated,&nbsp; &nbsp; redirectTo: state.auth.redirectTo, // <-- here&nbsp; &nbsp; error: state.error});export default connect(mapStateToProps, { login, clearErrors })(LoginForm);接口.ts:export interface IAuthReduxProps {&nbsp; auth: { isAuthenticated: boolean, redirectTo: string }; // <-- here added redirectTo&nbsp; error: IError;}authReducer.ts:case REGISTER_SUCCESS:&nbsp; localStorage.setItem('token', action.payload.token);&nbsp; return {&nbsp; &nbsp; ...state,&nbsp; &nbsp; ...action.payload,&nbsp; &nbsp; isAuthenticated: true,&nbsp; &nbsp; isLoading: false,&nbsp; &nbsp; redirectTo: "/dd" // <-- here&nbsp; };
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答