我正在使用Redux Form。
如果数据发送成功,我想重置表格。
import React, { Component } from "react";
import {
BrowserRouter as Router,
Route,
Switch,
withRouter
} from 'react-router-dom';
import CommentForm from '../components/CommentForm';
import { connect } from "react-redux";
import {authHeader} from '../components/auth-header';
import $ from 'jquery';
import { reset, reduxForm } from 'redux-form';
const createBlogComment = (data) => {
return fetch(CelestialSettings.URL.api + '/comments', {
method: 'post',
headers: {
...authHeader(),
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
}).then(res => {
if (res.status === 401) {
$('.thecmstatus').removeClass('success').addClass('error').html('There is something wrong while posting a comment');
return false;
}
if (res.status === 400) {
$('.thecmstatus').removeClass('success').addClass('error').html('There is something wrong while posting a comment');
return false;
}
if (res.status === 201) {
$('.thecmstatus').removeClass('error').addClass('success').html('Your comment will be visible after approval');
setTimeout(function() {
$('.thecmstatus').html('');
}, 3000);
return true;
}
}).catch(err => err);
}
class CommentFormToAPI extends Component {
constructor(props) {
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(content) {
let APIdata = {...this.props.addComment, content:content.commentcontent};
createBlogComment(APIdata);
if(createBlogComment(APIdata)){
//I use this but it is wrong.
dispatch(reset('CommentForm'));
}
}
render() {
return (
<div>
<CommentForm onSubmit={this.handleSubmit}></CommentForm>
</div>
);
}
}
function mapStateToProps(state){
return {
addComment: state.addComment,
};
};
export default connect(mapStateToProps)(withRouter(CommentFormToAPI));
自API发送以来,我可以处理提交的内容,但是我不知道如何重置Redux表单。你能建议我吗?
我在这里看了一下,我使用了最后一种方式(D)。 https://redux-form.com/6.0.0-alpha.4/docs/faq/howtoclear.md/
非常感谢。
答案 0 :(得分:1)
将dispatch
传递到您的createBlogComment函数:
createBlogComment(APIdata, dispatch)
然后,如果201
响应:
if (res.status === 201) {
$('.thecmstatus').removeClass('error').addClass('success').html('Your comment will be visible after approval');
setTimeout(function() {
$('.thecmstatus').html('');
}, 3000);
dispatch(reset('YourFormName'));
return true;
}
请确保从reset
导入redux-form
函数。