如何解决登录后反应重定向调度
成功登录此类项目后,如何将我的网站重定向到首页:
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,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',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,'LOGIN_FAIL')
);
dispatch({
type: LOGIN_FAIL
});
});
};
catch错误返回“错误:无效的钩子调用。只能在函数组件的主体内部调用钩子...”
解决方法
像这样使用UseEffect()
:
import { useHistory } from 'react-router-dom';
//
const LoginForm = ({
isAuthenticated,redirectTo,// <-- here
error,login,clearErrors
}: ILoginForm) => {
const history = useHistory();
//
useEffect(() => {
if(redirectTo)
history.push(redirectTo);
});
}
const mapStateToProps = (state: IAuthReduxProps) => ({
isAuthenticated: state.auth.isAuthenticated,redirectTo: state.auth.redirectTo,// <-- here
error: state.error
});
export default connect(mapStateToProps,{ login,clearErrors })(LoginForm);
interface.ts:
export interface IAuthReduxProps {
auth: { isAuthenticated: boolean,redirectTo: string }; // <-- here added redirectTo
error: IError;
}
authReducer.ts:
case REGISTER_SUCCESS:
localStorage.setItem('token',action.payload.token);
return {
...state,...action.payload,isAuthenticated: true,isLoading: false,redirectTo: "/dd" // <-- here
};
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。