我正在使用Create-React-App学习React Redux
我在商店,减速机,行动等方面遇到了麻烦。
我有一个简单的登录页面(省略了一些JSX以使其更易于阅读)
Login.js
import React, { Component } from "react";
import { connect } from "react-redux";
import * as actions from '../../actions';
import Logo from "../img/image-center.png";
import "./login.css";
class Login extends Component {
constructor(props){
super(props);
this.state = {
errorMsg : ""
};
this.loginClicked = this.loginClicked.bind(this);
console.log("loggedIn:", this.props.login);
}
loginClicked() {
try {
this.props.loginUser(this.refs.email.value, this.refs.password.value)
.then(() => {
console.log("thisprops", this.props);
});
}
catch(ex){
this.state.errorMsg = "Unable to connect to server";
console.log("error", ex);
}
}
render() {
return (
<div className="login-bg">
<div className="container signForm">
<div className="col s12 l6 login-form">
<p className="center-align">Login to Trade Portal</p>
<form>
<div className="row">
<div className="input-field">
<input id="email" type="email" className="validate" ref="email" />
<label htmlFor="email">Email</label>
</div>
</div>
<div className="row">
<div className="input-field">
<input id="password" type="password" className="validate" ref="password" />
<label htmlFor="password">Password</label>
</div>
</div>
<div className="row">
<button
className="btn waves-effect waves-light"
type="button"
name="action"
onClick={this.loginClicked}
>
Submit
</button>
<a href="/subcontractor" className="register">
Register here
</a>
</div>
<div className="row"><div style={{textAlign: "center", color:"red"}}>{this.props.login.message}</div></div>
</form>
</div>
</div>
</div>
</div>
);
}
}
function mapStateToProps({login}){
return { login } ;
}
export default connect(mapStateToProps, actions)(Login);
正如您所看到的,Log onClick函数调用了一个使用connect派生的prop loginUser(实际上调用了我的Action Login方法)
行动\ index.js
import axios from "axios";
import { FETCH_USER, LOGIN_USER, LOGIN_FAILED } from "./types";
export const fetchUser = () => async dispatch => {
const res = await axios.get("/api/Account/GetUser");
dispatch({ type: FETCH_USER, payload: res.data });
};
export const loginUser = (username, password) => async dispatch => {
try {
const res = await axios.post("/api/Account/Login", {username: username, password: password, persistant: false });
const message = res.data ? "" : "Incorrect username or password";
dispatch({ type: LOGIN_USER, payload: { success: res.data, message: message } });
}
catch(ex){
console.log("Login Failed:", ex);
dispatch({ type: LOGIN_FAILED, payload: { success: false, message: "Unable to connect to authentication server" } });
}
}
上面的代码调用我的服务器并登录用户,成功后它会在登录名Reducer.js中读取
import { LOGIN_USER, LOGIN_FAILED } from "../actions/types";
export default function(state = null, action) {
console.log(action);
switch (action.type) {
case LOGIN_USER:
return { success: action.payload.success, message: action.payload.message };
break;
case LOGIN_FAILED:
return { success: false, message: action.payload.message };
break;
default:
return { success: false, message: ""};
}
}
现在我的问题是我在哪里以及如何重定向用户成功登录主页? “/家”
我希望我可以在某个地方使用Login.js,因为有一天我可能想要有2个登录路由(即如果从头部登录它可能不会重定向到主页,但是当从Login.js登录时它应该记录进入家庭)。因此我不认为这个动作应该在Action或Reducer中。但我不确定如何在Login.js中绑定它,所以当登录成功时,重定向
可能的方法 -
1-成功登录后重定向从loginClicked方法(内部.then),如下所示:
loginClicked() {
try {
this.props.loginUser(this.refs.email.value, this.refs.password.value)
.then(() => {
this.props.history.push('/home');
});
}
catch(ex){
this.state.errorMsg = "Unable to connect to server";
console.log("error", ex);
}
}
2-或者另一个选项是将检查放在render方法中,每当存储发生任何更改时,它将重新呈现组件,如果你发现success == true
重定向到主页,就像这样:
render(){
if(this.props.success)
return <Redirect to="/home" />
return (....)
}
如果您遵循第一种方法,那么您还需要将检查放在componentDidMount
方法中,如果用户想在登录成功后打开登录页面,请重定向到主页。您正在通过bool success
维护登录会话,检查bool值。
componentDidMount(){
if(this.props.success) {
this.props.history.push('/home');
}
}
建议:
根据DOC,避免使用字符串引用:
如果您之前使用过React,那么您可能熟悉旧的API,其中ref属性是一个字符串,如“textInput”,DOM节点作为this.refs.textInput访问。我们建议不要使用它,因为字符串引用有一些问题,被认为是遗留问题,很可能会在未来的某个版本中删除。如果您当前正在使用this.refs.textInput访问引用,我们建议使用回调模式。
Redux-thunk将返回你从thunk返回的任何内容,这意味着如果你返回一个promise(你已经在做了因为它是一个async
函数),你可以简单地在Login.js中等待它,然后执行重定向。
看起来你可以简单地修改在调用console.log("thisprops", this.props);
来执行重定向之后发生的Login.js中的loginUser
。
您可以在反应生命周期中执行此操作。
componentWillReceiveProps(nextProps) {
if (nextProps.login.success && nexProps.login.success !== this.props.login.success) {
this.props.history.push('/home');
}
}