[英]alternatives to componentDidMount....Axios?
我最近為一項新工作做了一些 API 測試。 只是接收數據並傳遞它。 盡管我已經完成了任務並且它可以正常工作,但與我一起走過它的人並不是 componentDidMount 的忠實粉絲。
他們不建議替代方案嗎? 有誰知道為什么會這樣? 是因為它是異步的嗎?
新的現代方法是: useEffect
首先是一些代碼(來自文檔):
// Similar to componentDidMount and componentDidUpdate:
useEffect(() => {
// Update the document title using the browser API
document.title = `You clicked ${count} times`;
});
歸根結底,componentDidMount 的目的是執行某些事情(副作用),因為組件已安裝(原因或事件)。
因此,您可以像這樣指定重新運行的依賴項(或原因)數組:
useEffect(() => {
// ....
}, [someVar]);
所以如果someVar
改變了,function 將重新運行。
特殊用例是; 省略此參數,將導致它運行一次,即掛載事件。 並指定空數組將導致它在每次重新渲染時運行。
componentWillUnmount
:只需從內部 function 返回一個 function ,如下所示:
useEffect(() => {
function handleStatusChange(status) {
setIsOnline(status.isOnline);
}
ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);
// Specify how to clean up after this effect:
return function cleanup() {
ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);
};
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.