[英]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 =值=> {const錯誤= {} if(!values.password){errors.password ='必需'} else if(values.password.length> 15){errors.password ='必須為15個字符或較少'} if(!values.email){errors.email ='必需'} else if(!/ ^ [A-Z0-9 ._%+-] + @ [A-Z0-9 .-] +。 [AZ] {2,4} $ / i.test(values.email)){errors.email ='無效的電子郵件地址'}返回錯誤}
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 &&
{警告}))} )
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;
我收到此錯誤:
未捕獲的錯誤:您必須將handleSubmit()傳遞給onSubmit函數,或者將onSubmit傳遞為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()));
};
}
這是超級超級快的寫法,所以我不確定它是否有效。 這只是“偽代碼”,解釋了我將如何管理您的問題的解決方案。
看看redux-form( https://redux-form.com/6.1.0/docs/api/selectors.md )的getFormValues
。
希望能幫助到你。 干杯。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.