[英]React Class passing stale props to Child stateless component
我的父組件代表一個表單。 填寫表單的用戶可以訪問表單中的信息,這些信息會在他們更新某些字段時實時更新。 我遇到的問題是。 當我們獲取新數據並將其隨機傳遞給孩子時,在這些更新之一中,有時孩子會收到陳舊的道具。 來自上一個請求。 結構是這樣的。
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 > 容器接收先前的請求響應數據。 如何阻止父級傳遞陳舊數據?
這里的問題是當fetchUpdates
調用fetchUpdates
時,它會由於網絡延遲而fetchUpdates
。 假設fetchUpdates
被調用了 3 次,假設請求分別需要fetchUpdates
和 4 秒才能完成。 在這種情況下,您可以看到第二個請求在第一個請求之前調用了setState
。 結果,信息組件在第二個值之后傳遞第一個值。 這就是它間歇性的原因。
在這里使用 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 }))
}
將不起作用,因為這意味着當網絡呼叫正在進行時您將錯過按鍵。
我建議對輸入使用去抖動。 您可以在此處找到如何進行去抖動: 在 React.js 中執行去抖動
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.