[英]Component does not update after props change with componentDidUpdate
[英]ReactJS componentDidUpdate not called even after props change
我正在使用 Draft-js 進行反應,我在其中進行 api 調用(在功能父組件中)並獲取要放在編輯器中的內容。 我有這段代碼在收到道具后將獲取的數據插入編輯器:
父組件:
var draftContent = "";
var isContentFetched = false;
const CommentSection = () => {
let response = await fetch(url, {
method: "get",
headers: headers,
});
let query = await response.json(); // read response body and parse as JSON
draftContent = element.comment;
isContentFetched = true;
return(<RichTextEditor
isDraftFetched={isDraftFetched}
isContentFetched={isContentFetched}
placeholder=""
rows={6}
boxWidth="100%"
boxHeight="155px"
/>)
})
編輯器組件:
componentDidUpdate(props) {
if(this.props.isContentFetched == true && draftAlreadyFilled== false) {
this._insertText(this.props.draftContent);
draftAlreadyFilled = true;
}
}
_insertText(htmlContent) {
this.setState({
editorState: EditorState.createWithContent(
ContentState.createFromBlockArray(
convertFromHTML(htmlContent)
)
),
})
}
問題是,通過 props 加載和發送的文本沒有填滿編輯器。 相反,一旦我進入頁面並單擊刷新,它就會正常加載。
PS:1.我檢查了相關問題,這些解決方案都不起作用。 2.我在父組件中進行API調用確實很有必要。
從外部 api 獲取數據是一個副作用。使用 useEffect Hook 代替。在 ajax 調用內部使用 function 傳遞給 useEffect 方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.