亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

useEffect 作為 componentWillUnmount

useEffect 作為 componentWillUnmount

慕桂英4014372 2023-07-14 10:43:40
我正在嘗試將舊的類組件重構為帶鉤子的功能組件,但陷入了困境componentWillUnmount之前的代碼是這樣的: componentDidMount() {        this.isDropdownMounted = true;  }   componentWillUnmount() {          this.isDropdownMounted = false;  }我的解決方案是使用useEffect帶有清理功能的 a ,但盡管它“看起來”可以工作,但代碼審查失敗,我似乎找不到更好的解決方案。我讀過有關可能使用 a 的內容,useRef但尚未偶然發現類似的用例。  useEffect(() => {    isDropdownMounted = true;    return function cleanup() {      isDropdownMounted = false;    };  }, []);我可以嘗試什么想法嗎?
查看完整描述

2 回答

?
人到中年有點甜

TA貢獻1895條經驗 獲得超7個贊

useEffect允許您返回一個清理函數,該函數將在組件卸載時運行。

注意:只要依賴數組中的某些內容發生更改,它也會運行useEffect。它向您保證您將始終獲得“新鮮”的效果。

通過清理來響應文檔useEffect。

這是他們使用的示例:

使用類:

componentDidMount() {

? ? ChatAPI.subscribeToFriendStatus(

? ? ? this.props.friend.id,

? ? ? this.handleStatusChange

? ? );

? }


componentWillUnmount() {

? ChatAPI.unsubscribeFromFriendStatus(

? ? this.props.friend.id,

? ? this.handleStatusChange

? );

}

使用鉤子:


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);

? };

});

這是一個工作示例:


function App() {


? const [boolean,setBoolean] = React.useState(true);

??

? const toggleBoolean = () => setBoolean((prevState) => !prevState);


? return(

? ? <div>

? ? ?{ boolean ?

? ? ? ? ?<Component1/>

? ? ? ?: <Component2/>

? ? ?}

? ? ? ?<button onClick={toggleBoolean}>Toggle</button>

? ? ?</div>

? );

}


function Component1() {


? React.useEffect(() => {

? ? console.log("Component1 has mounted...");

? ? return () => { console.log("Component1 has unmounted...")};

? },[]);


? return(

? ? <div>Component1</div>

? );

}


function Component2() {

? return(

? ? <div>Component2</div>

? );

}


ReactDOM.render(<App/>, document.getElementById("root"));

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>

<div id="root"/>


查看完整回答
反對 回復 2023-07-14
?
大話西游666

TA貢獻1817條經驗 獲得超14個贊

React 不記得 isDropdownMounted 變量。它將在每次渲染時重新創建。最好使用 useRef 鉤子來設置 useEffect 中的值并在下次渲染時記住它。


const isDropdownMounted = useRef(null);


useEffect(() => {

    isDropdownMounted.current = true;


    return function cleanup() {

      isDropdownMounted.current = false;

    };

  }, []);


查看完整回答
反對 回復 2023-07-14
  • 2 回答
  • 0 關注
  • 160 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號