“我的父组件”代表一个表单。 填写表单的用户可以访问表单中的信息,这些信息会在他们更新某些字段时实时更新。 我遇到的问题是。在这些更新之一中,当我们获取新数据并将其随机传递给孩子时,有时孩子会收到陈旧的道具。来自上一个请求。 结构是这样的。
export class Form extends React.Component<Props, State> {
fetchUpdates = async (payload) => {
this.setState({ isLoadingUpdates: true })
await Service.getUpdates(payload)
.then(response => {
this.setState({ isLoadingUpdates: false, updates: response.data })
})
.catch(({ data: errors }) => this.setState({ isLoadingUpdates: false }))
}
}
render () {
const {
updates,
isLoadingUpdates,
} = this.state
<FormCombobox
onChange={this.fetchUpdates}
md={10}
name="field"
id="field"
label="Field"
onMenuOpen={() => forceCheck()}
openMenuOnClick
selectRef={this.itemSelect}
value={values.item}
options={itemOptions || []}
/>
<Info
data={updates}
errorMessage={this.state.updatesError}
/>
}
}
它不会每次都出现,而是在第一次更新表单时或在以下更新之一时随机发生,
答案 0 :(得分:0)
这里的问题是,fetchUpdates
被多次调用时,由于网络延迟而混乱。假设fetchUpdates
被调用了3次,并且说该请求分别需要5、2和4秒才能完成。在这种情况下,您可以看到第二个请求在第一个请求之前调用setState
。结果,info组件在第二个值之后传递第一个值。这就是它断断续续的原因。
在这里使用await不会有帮助,因为fetchUpdates
函数调用是相互独立的。
还有一件事,我注意到您有isLoadingUpdates
。但是它没有在代码中的任何地方使用。而且也在做,
if (!this.state. isLoadingUpdates) {
await Service.getUpdates(payload)
.then(response => {
this.setState({ isLoadingUpdates: false, updates: response.data })
})
.catch(({ data: errors }) => this.setState({ isLoadingUpdates: false }))
}
无效,因为那样一来,这意味着您在进行网络通话时会错过按键。
我建议对输入使用去抖。您可以在这里找到如何进行反跳:Perform debounce in React.js