[英]How to call child component method from parent component method only after subscribing httpClient observables?
[英]How to call method in child component only once after parent state update
我有一個父母和一個孩子。 父組件使用 fetch 請求檢索數據(數據被命名為 blurts),並通過 props 將數據發送到子組件。 子組件是一個惰性加載器組件,在用戶滾動時一次只顯示 6 條記錄。
惰性組件根據父組件記錄的數量創建自己的狀態(數組),這決定了記錄是否應該可見。 所有 isVisible 屬性最初都設置為 false。
惰性組件中的 componentDidMount():
componentDidMount() {
var isVisibleArray = this.props.blurts.map(item => {
return false;
});
this.setState({ isVisible: isVisibleArray });
this.PushBlurtArray();
window.addEventListener('scroll', this.LazyLoader);
}
然后,調用 PushBlurtArray() 方法以將前 6 條記錄設置為可見。 每次用戶滾動到第六條記錄時也會調用此方法。 延遲加載器中的內部狀態會對此進行跟蹤,並根據需要將另外 6 個設置為可見。
惰性組件中的 PushBlurtArray():
PushBlurtArray() {
// Initial values that keep track of lazy state.
var renderCount = this.state.lazyState.skipCount,
numRendered = this.state.numberRendered,
isVisibleUpdate = this.state.isVisible;
// Logic to get the next 6 (or less) blurts in the array and set isVisible to true
// each time this method is called by the lazyloader method.
for(let i=numRendered; i<renderCount; i++) {
if (this.props.blurts[i]) {
isVisibleUpdate[i] = true;
numRendered++;
}
}
// Update state accordingly so the loop iterates over the proper numerical
// sequence keeping the blurts in order of consecutive sixes.
this.setState(prevState => ({
lazyState: {
lzyLoading: true,
skipCount: prevState.lazyState.skipCount + prevState.lazyState.skipInc,
skipInc: 6,
skipDb: prevState.lazyState.skipDb
},
isVisible: isVisibleUpdate,
numberRendered: numRendered
}));
}
這在一定程度上可以正常工作。 我遇到的限制是父組件只提取 42 條記錄的初始計數。 然后,一旦惰性加載器遍歷了所有 42 條記錄,我就會調用父級中的一個方法,該方法將另外 42 條記錄安裝到其狀態,進而重新呈現惰性加載器。 從理論上講,這應該無限期地繼續下去而不會出現問題。
我遇到的問題是,一旦將 42 條附加記錄添加到父狀態,就需要調用 PushBlurtArray()。 如果我在 render() 方法或 componentDidUpdate() 中調用 PushBlurtArray(),它最終會重復調用 PushBlurtArray(),這幾乎搞砸了整個過程。
在將 42 條記錄添加到父組件中的 state 之后,我需要一種方法來調用 PushBlurtArray() 一次。
您可以在componentDidUpdate
檢查數據的轉換。 在這種情況下,您要檢查數組的長度以確定它何時發生變化。
componentDidUpdate(props) {
if (
(this.props.blurts.length > 0 && !props.blurts.length) ||
this.props.blurts.length !== props.blurts.length
) {
this.PushBlurtArray();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.