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

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

本機反應 - 為計時器應用程序優化 ReactJS 代碼

本機反應 - 為計時器應用程序優化 ReactJS 代碼

蝴蝶刀刀 2022-09-29 16:57:23
我目前正在將我的 ReactJS 代碼移動到 React Native,我想知道我是否需要以任何方式更新它。它正在工作,但我相信某個地方可能存在內存泄漏(我在運行應用程序時收到警告)。我所指的部分是:class Stopwatch extends Component {  constructor() {    super();    this.state = {      timerOn: false,      timerStart: 0,      timerTime: 0    };  }  startTimer = () => {        this.setState({          timerOn: true,          timerTime: this.state.timerTime,          timerStart: Date.now() - this.state.timerTime,        });        this.timer = setInterval(() => {          this.setState({            timerTime: Date.now() - this.state.timerStart          });        }, 10);      };        stopTimer = () => {        this.setState({           timerOn: false,        });        clearInterval(this.timer);      };    render() {        return (              <View>                  {this.state.timerOn === false && this.state.timerTime === 0 && (                    <TouchableOpacity style={styles.button} onPress={this.startTimer}>                      <Text>start</Text>                    </TouchableOpacity>                   )}                  {this.state.timerOn === true && (                    <TouchableOpacity style={styles.button} onPress={this.stopTimer}>                      <Text>stop</Text>                    </TouchableOpacity>                  )}              </View>}<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
查看完整描述

1 回答

?
斯蒂芬大帝

TA貢獻1827條經驗 獲得超8個贊

如果組件在計時器運行時卸載,則會發現內存泄漏。這是因為集合間隔永遠不會被清除;間隔回調仍將觸發,并且由于它調用 setState,因此即使組件不再掛載,它也會嘗試更新組件(導致錯誤消息)

要解決此問題,您只需要使用組件“將卸載”生命周期方法清除 setInterval。

https://reactjs.org/docs/state-and-lifecycle.html


查看完整回答
反對 回復 2022-09-29
  • 1 回答
  • 0 關注
  • 96 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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