我的父组件表示一个表单。填写表单的用户可以访问表单中的信息,这些信息在他们更新某些字段时会实时更新。我遇到的问题是。在这些更新中,当我们获取新数据并将其随机传递给孩子时,孩子有时会收到陈旧的道具。来自上一次请求。它的结构是这样的。
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}
/>
}
}它不是每次都会发生,而是随机发生的,无论是在表单第一次更新时,还是在随后的某个更新中,< Info >容器都会接收到以前的请求响应数据。如何才能阻止父进程传递过时的数据?
发布于 2020-09-04 03:06:40
这里的问题是,当fetchUpdates被多次调用时,由于网络延迟,它会变得无序。假设fetchUpdates被调用了三次,请求分别需要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
https://stackoverflow.com/questions/63729835
复制相似问题