所以我希望能够在用户成功登录后转到主页面。我还是 React 的新手。如何才能做到这一点。我也在使用 v4 的 react。当我点击登录按钮时,它似乎触发了操作但没有完成它。
这是处理登录的操作:
const mainPage = (response, dispatch) => {
if(POST_DATA_SUCCESS) {
this.props.history.push('/main');
}
dispatch({
type: POST_DATA_SUCCESS,
response,
});
};
export function loginUser(username1, password1) {
const promise = fetch('http://localhost:8080/users/login', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Basic ' + btoa(username1 + ":" + password1),
},
body: JSON.stringify({
username: username1,
password: password1,
})
});
return {
onRequest: POST_DATA_TRIGGERED,
onSuccess: mainPage,
onFailure: POST_DATA_FAILURE,
promise,
};
}
这是处理登录请求的后端:
router.get('/login',
passport.authenticate('basic', {session: false}),
(req, res) => res.json({user: req.user.apiRepr()})
);
router.post('/login', function (req, res, next) {
passport.authenticate('basic', function (err, user, info) {
if (err) {
return console.log(err);
}
if (!user) {
return res.status(401).json({
message: 'Username/Password Incorrect'
});
}
req.logIn(user, function (err) {
if (err) {
return console.log(err);
}
return res.status(200).json({
user: user.username
});
});
})(req, res, next);
});
以及带有表单的登录组件:
import React from 'react';
import {BrowserRouter as Router, Route, Link} from 'react-router-dom';
import { loginUser } from '../actions';
import { connect } from 'react-redux';
export class Login extends React.Component {
constructor(props) {
super(props);
this.state = {
//username: '',
//password: '',
}
}
render() {
return(
<form>
<h3>Login to start your Journey</h3>
<input placeholder="username" ref={input => {this.username = input}}>
</input>
<input placeholder="password" type="password"ref={input => {this.password
= input}}></input>
<button onClick={this.login.bind(this)}>Login</button>
</form>
)
}
login() {
const userName = this.username.value;
const passWord = this.password.value;
console.log(userName);
console.log(passWord);
this.props.loginUser(userName, passWord);
}
}
export default connect(null, { loginUser })(Login);
在您的 mainPage 动作创建者中,您使用this
假设绑定到组件实例来引用道具。不是。
const mainPage = (response, dispatch) => {
if(POST_DATA_SUCCESS) {
this.props.history.push('/main'); // 'this' here does not refer to the React component instance
}
dispatch({
type: POST_DATA_SUCCESS,
response,
});
};
如果您使用的是react-router
v4,则可以使用react-router-redux
, 和 import push
,这是一个将由路由器减速器处理的动作创建者。您需要先按照此处的步骤设置您的 redux 存储
import { push } from 'react-router-redux'
const mainPage = (response, dispatch) => {
if(POST_DATA_SUCCESS) {
dispatch(push('/main'));
}
dispatch({
type: POST_DATA_SUCCESS,
response,
});
};
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句