我正在向后端提交一个表单,然后重新渲染组件以获取新项目的列表。现在我正在组件DidUpdate函数中进行重新渲染:
componentDidUpdate() {
this.props.fetchListStart();
}
我的提交表单如下所示:
<form
onSubmit={e => {
e.preventDefault();
this.props.submit();
this.props.close();
}}
>
<div className="row" style={{ textAlign: 'start' }}>
Do you really want?
<div className="col-md-12 buttonContainer">
<ButtonA
label="Submit"
style={{ width: '50%' }}
primary
type="submit"
/>
</div>
</div>
</form>
所以问题是,有时组件DidUpdate触发得比我在数据库中提交更新数据更快。我应该如何检查我的提交是否已完成?
将 fetchListStart(( 移动到更新函数的回调。
例如:
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
fetchListStart();
})
.catch(function (error) {
console.log(error);
});
从您的问题来看,您似乎需要在发布到 db 的方法的成功回调中调用父组件的 setState 函数。然后调用 fetchListStart 作为对 setState 的回调。
例如
class ParentComponent extends React.Component{
submit(){
fetch("/data").then(response=>{
this.setState({
data:response
},this.fetchListStart())
})
}
render(){
return <ChildComponent {...this.state} submit={this.submit} />
}
}
我假设您只需要在呈现视图后获取数据列表。setState(( 的第二个参数是一个可选的回调函数,一旦 setState 完成并重新呈现组件,它将执行该函数。