如何在 React JS 中使用 Redux 和 Axios?
How to use Redux and Axios in React JS?
这是我的登录页面:
class Login extends Component {
/*define constructor for state props*/
constructor() {
super();
this.state = {
email: '',
password: ''
};
this.handleSubmit = this.handleSubmit.bind(this);
this.handleChange = this.handleChange.bind(this);
}
/*Define the after submit form*/
handleSubmit(e) {
// Stop browser from submitting the form.
e.preventDefault();
this.form.validateFields();
if (!this.form.isValid()) {
console.log("Not valid arguments");
} else {
This is my function for Axios post values
Validate here or directly when setting state.
Then send a POST request to your endpoint.
axios.post('http//127.0.0.1:8000/user/login', {
email: this.state.email,
password: this.state.password
})
.then(function(response) {
/*response from json*/
console.log(response);
})
.catch(function(error) {
console.log(error);
});
}
}
handleChange(e) {
this.form.validateFields(e.currentTarget);
this.setState({
[e.target.name]: e.target.value
});
}
render() {
return(
<div className="container">
<h3 className="jumbotron">Redux Form Validation</h3>
<FormCode onSubmit={this.submit} />
</div>
这是我使用 redux-forms 进行验证的函数
在前面定义验证
const validate = values => {
const errors = {}
if (!values.password) {
errors.password = 'Required'
} else if (values.password.length > 15) {
errors.password = 'Must be 15 characters or less'
}
if (!values.email) {
errors.email = 'Required'
} else if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+.[A-Z]{2,4}$/i.test(values.email)) {
errors.email = 'Invalid email address'
}
return errors
}
const renderField = ({ input, label, type, meta: { touched, error, warning } }) => (
<div>
<label className="control-label">{label}</label>
<div>
<input {...input} placeholder={label} type={type} className="form-control" />
{touched && ((error && <span className="text-danger">{error}</span>) || (warning &&
{warning}))}
)
let FormCode = props => {
const { handleSubmit, pristine, submitting } = props;
return (
<form onSubmit={ handleSubmit }>
<div className="form-group">
<Field name="firstName" component={renderField} label="First Name" />
</div>
<div className="form-group">
<Field name="lastName" component={renderField} label="Last Name" />
</div>
<div className="form-group">
<Field name="email" component={renderField} label="Email" />
</div>
<div className="form-group">
<button type="submit" disabled={pristine || submitting} className="btn btn-primary">Submit</button>
</div>
</form>
)
}
FormCode = reduxForm({
form: 'contact',
validate,
})(FormCode);
export default FormCode;
我收到此错误:
Uncaught Error: You must either pass handleSubmit() an onSubmit
function or pass onSubmit as a prop
试试这个:
onSubmit(values) {
// this === component
console.log(values);
}
render() {
// this is a property that is being passed to your component
// on behalf of reduxForm
const {handleSubmit} = this.props
return (
// handleSubmit takes a function that you define and you
// pass that to handleSubmit and it takes care of the
// reduxForm validation and if everything is good then it
// will call the callback this.onSubmit and passes the values
// out of the form to work with
// this.onSubmit is the callback function
<form onSubmit={handleSubmit(this.onSubmit.bind(this))}>
<Field
label="Title For Post"
name="title"
component={this.renderField}
/>
<Field
label="Categories"
name="categories"
component={this.renderField}
/>
<Field
label="Post Content"
name="content"
component={this.renderField}
/>
<button type="submit" className="btn btn-primary">Submit</button>
</form>
);
}
以上解决方案可行。不管怎样,我想给你留下我的意见。
首先,你不应该混合使用 setState
和 Redux。如果你打算使用 Redux,那么最好在 Redux 上处理所有应用程序的状态。
然后,在您的 React 组件中,您应该只调用 Redux 的操作。假设您有一个名为 loginWithEmailAndPassword
的操作。您的提交功能将是这样的:
handleSubmit(e) {
e.preventDefault();
// There is not need to pass email and password since you have
// those values in "state".
this.props.loginWithEmailAndPassword();
}
而您的 Redux 操作将是这样的:
export function loginWithEmailAndPassword() {
return (dispatch, getState) => {
// Get email and password from state.
return axios.post('YOUR_URL', { email, password })
.then((success) => success && dispatch(someNextAction()));
};
}
写的超级超级快,所以我不确定它是否有效。这只是 "pseudo-code" 解释了我将如何管理您的问题的解决方案。
看看 getFormValues
的 redux-form (https://redux-form.com/6.1.0/docs/api/selectors.md)。
希望对您有所帮助。
干杯。
这是我的登录页面:
class Login extends Component {
/*define constructor for state props*/
constructor() {
super();
this.state = {
email: '',
password: ''
};
this.handleSubmit = this.handleSubmit.bind(this);
this.handleChange = this.handleChange.bind(this);
}
/*Define the after submit form*/
handleSubmit(e) {
// Stop browser from submitting the form.
e.preventDefault();
this.form.validateFields();
if (!this.form.isValid()) {
console.log("Not valid arguments");
} else {
This is my function for Axios post values
Validate here or directly when setting state.
Then send a POST request to your endpoint.
axios.post('http//127.0.0.1:8000/user/login', {
email: this.state.email,
password: this.state.password
})
.then(function(response) {
/*response from json*/
console.log(response);
})
.catch(function(error) {
console.log(error);
});
}
}
handleChange(e) {
this.form.validateFields(e.currentTarget);
this.setState({
[e.target.name]: e.target.value
});
}
render() {
return(
<div className="container">
<h3 className="jumbotron">Redux Form Validation</h3>
<FormCode onSubmit={this.submit} />
</div>
这是我使用 redux-forms 进行验证的函数
在前面定义验证
const validate = values => { const errors = {} if (!values.password) { errors.password = 'Required' } else if (values.password.length > 15) { errors.password = 'Must be 15 characters or less' } if (!values.email) { errors.email = 'Required' } else if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+.[A-Z]{2,4}$/i.test(values.email)) { errors.email = 'Invalid email address' } return errors }
const renderField = ({ input, label, type, meta: { touched, error, warning } }) => ( <div> <label className="control-label">{label}</label> <div> <input {...input} placeholder={label} type={type} className="form-control" /> {touched && ((error && <span className="text-danger">{error}</span>) || (warning &&
{warning}))} )
let FormCode = props => { const { handleSubmit, pristine, submitting } = props; return ( <form onSubmit={ handleSubmit }> <div className="form-group"> <Field name="firstName" component={renderField} label="First Name" /> </div> <div className="form-group"> <Field name="lastName" component={renderField} label="Last Name" /> </div> <div className="form-group"> <Field name="email" component={renderField} label="Email" /> </div> <div className="form-group"> <button type="submit" disabled={pristine || submitting} className="btn btn-primary">Submit</button> </div> </form> ) } FormCode = reduxForm({ form: 'contact', validate, })(FormCode);
export default FormCode;
我收到此错误:
Uncaught Error: You must either pass handleSubmit() an onSubmit function or pass onSubmit as a prop
试试这个:
onSubmit(values) {
// this === component
console.log(values);
}
render() {
// this is a property that is being passed to your component
// on behalf of reduxForm
const {handleSubmit} = this.props
return (
// handleSubmit takes a function that you define and you
// pass that to handleSubmit and it takes care of the
// reduxForm validation and if everything is good then it
// will call the callback this.onSubmit and passes the values
// out of the form to work with
// this.onSubmit is the callback function
<form onSubmit={handleSubmit(this.onSubmit.bind(this))}>
<Field
label="Title For Post"
name="title"
component={this.renderField}
/>
<Field
label="Categories"
name="categories"
component={this.renderField}
/>
<Field
label="Post Content"
name="content"
component={this.renderField}
/>
<button type="submit" className="btn btn-primary">Submit</button>
</form>
);
}
以上解决方案可行。不管怎样,我想给你留下我的意见。
首先,你不应该混合使用 setState
和 Redux。如果你打算使用 Redux,那么最好在 Redux 上处理所有应用程序的状态。
然后,在您的 React 组件中,您应该只调用 Redux 的操作。假设您有一个名为 loginWithEmailAndPassword
的操作。您的提交功能将是这样的:
handleSubmit(e) {
e.preventDefault();
// There is not need to pass email and password since you have
// those values in "state".
this.props.loginWithEmailAndPassword();
}
而您的 Redux 操作将是这样的:
export function loginWithEmailAndPassword() {
return (dispatch, getState) => {
// Get email and password from state.
return axios.post('YOUR_URL', { email, password })
.then((success) => success && dispatch(someNextAction()));
};
}
写的超级超级快,所以我不确定它是否有效。这只是 "pseudo-code" 解释了我将如何管理您的问题的解决方案。
看看 getFormValues
的 redux-form (https://redux-form.com/6.1.0/docs/api/selectors.md)。
希望对您有所帮助。 干杯。