我已经在React中创建了一个表单,每次提交后都会清除。但是,如果提交不成功(例如,如果用户不正确地填写了字段),则也会清除该表单。这当然很烦人,因为用户必须重复数据输入的整个过程。因此,我要实施的清除是仅在成功提交后才激活的清除。如果提交不成功,数据将保留在表单中,以便用户可以对数据进行重做。
要管理状态,请使用Redux。
提交功能
onSubmit = e => {
e.preventDefault();
let { title, content, audio} = this.state;
let formDataStory = new FormData(); // create form formData
formDataStory.append('audio', audio); // add audio to formData
formDataStory.append('title', title); // add title to formData
formDataStory.append('content', content); // add content to formData
this.props.addStory(formDataStory); // call addStory function with formDataStory as Input to create new Story
this.setState({
title: "", // clear title field after submission
content:"", // clear content field after submission
});
this.inputRef.current.value = ''; // clear file field after submission
};
添加故事动作
export const addStory = formDataStory => (dispatch, getState) => {
axios.post(apiBase +"/story/", formDataStory, tokenConfig(getState) )
.then(res => {
dispatch(createMessage({ addStory: "Story Added" }));
dispatch({
type: ADD_STORY,
payload: res.data
});
})
.catch(err =>
dispatch(returnErrors(err.response.data, err.response.status))
);
};
目前,我不知道该如何实现,也没有很好地阅读它(我的假设是这样的:如果成功添加了故事,则->格式清晰,否则- >保留表格)。我对此感到很高兴。
答案 0 :(得分:1)
You can use a .then and .catch after calling "this.props.addStory(formDataStory)" if you use a promise in addStory definition:
export const addStory = formDataStory => (dispatch, getState) =>
new Promiuse((resolve, reject) => {
axios.post(apiBase +"/story/", formDataStory, tokenConfig(getState) )
.then(res => {
dispatch(createMessage({ addStory: "Story Added" }));
dispatch({
type: ADD_STORY,
payload: res.data
});
resolve(res);
})
.catch(err => {
reject(err);
dispatch(returnErrors(err.response.data, err.response.status))
}
);
});
And then:
onSubmit = e => {
e.preventDefault();
let { title, content, audio} = this.state;
let formDataStory = new FormData(); // create form formData
formDataStory.append('audio', audio); // add audio to formData
formDataStory.append('title', title); // add title to formData
formDataStory.append('content', content); // add content to formData
this.props.addStory(formDataStory)
.then(() => {
this.setState({
title: "", // clear title field after submission
content:"", // clear content field after submission
});
this.inputRef.current.value = ''; // clear file field after submission
}) // call addStory function with formDataStory as Input to create new Story
};
答案 1 :(得分:1)
在redux中,它的过程更长一些,但是没有其他选择。 首先在axios req由于某些错误而失败时检入操作,因此请调用dispatch mathod并传递dispatch({type:ERROR,payload:err.message}),然后在减速器中淡化布尔值,例如在减速器set isError的初始状态下: false,但是当action发送的action.type为ERROR时,则在这种情况下将isError false更改为true。然后在主comp调用中使用mapstatetoProps调用isError,并检查来自redux的具有isError属性true的props或isError为false,然后清除表单,否则为空