我尝试使用redux-form创建表单并在基于react-redux-starter-kit的项目中使用
这是我的容器
import { connect } from 'react-redux'
import { loginUser, logoutUser } from '../modules/login'
import Login from '../components/Login'
const mapDispatchToProps = {
loginUser,
logoutUser,
};
const mapStateToProps = state => ({
errorMessage: state.errorMessage,
});
export default connect(mapStateToProps, mapDispatchToProps)(Login)
,这是表格
import React, { PropTypes } from 'react';
import { Input, Button, Card, CardText, CardTitle } from 'react-toolbox';
import { Field, reduxForm } from 'redux-form';
const Login = props => (
<form onSubmit={props.loginUser}>
<div>
<label htmlFor="email">Email</label>
<Field name="email" component="input" type="email"/>
</div>
<div>
<label htmlFor="password">Password</label>
<Field name="password" component="input" type="password"/>
</div>
<button type="submit">Submit</button>
</form>
);
export default reduxForm({ form: 'login' })(Login);
loginUser
函数看起来像
export function loginUser(creds) {
const config = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
email: creds.email,
password: creds.password,
}),
};
return (dispatch) => {
dispatch(requestLogin(creds))
return fetch('http://localhost:3001/auth/login', config)
.then(response => response.json().then(user => ({ user, response })))
.then(({ user, response }) => {
if (user.errors) {
const errors = user.errors.map(error => error.detail);
dispatch(loginError(errors))
return Promise.reject(loginError(errors));
}
dispatch(receiveLogin(user));
})
.catch(err => console.log('Error: ', err));
};
}
此功能已被调用,但我已重定向到
http://localhost:3000/login?email=test%40test.com&password=test
我无法找到原因。你有什么想法吗?
以下是行动
function requestLogin(creds) {
return {
type: LOGIN_REQUEST,
isFetching: true,
isAuthenticated: false,
creds,
};
}
function receiveLogin(user) {
return {
type: LOGIN_SUCCESS,
isFetching: false,
isAuthenticated: true,
id_token: user.id_token,
};
}
function loginError(message) {
return {
type: LOGIN_FAILURE,
isFetching: false,
isAuthenticated: false,
message,
};
}
答案 0 :(得分:4)
修改表单onSubmit as-
<form onSubmit={props.handleSubmit(props.loginUser)}>
</form>