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

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

react native 功能組件中構造函數的解決方案是什么?

react native 功能組件中構造函數的解決方案是什么?

慕妹3146593 2022-11-11 16:57:46
讓我帶你解決我的問題。我正在制作一個計時器功能組件,我將 startValue 傳遞給組件,然后該組件將使用通過 props 傳遞的 startValue 啟動計時器(以秒為單位減少一秒)。const FunctionalComponent = (props: any) => {const [timerValue, setTimerValue] = useState(props.initialValue)console.log('Set State')useEffect(() => {    console.log('UseEffects called')    setInterval(() => {        setTimerValue(timerValue - 1)    }, 1000)}, [])return <View><Text style={styles.textStyle}>{timerValue}</Text></View>}我在 Parent 中的渲染功能。render() {    return <View style={styles.mainView}>        <FunctionalComponent  initialValue={30} />    </View>}現在,每次 react 重新渲染父組件時,FunctionalComponent 都會被調用并重置 timerValue 值。我使用類組件構造函數解決了這個問題,但我想知道在功能組件中是否有任何解決方案可以做到這一點。class OTPTimer extends Component {    constructor(props: any) {        super(props)        this.state = {            timeLeft: props.fromStart        }        if (props.startTimer) {            this.startTimer()        }    }    componentDidUpdate(prevProps: any) {        if (!prevProps.startTimer && this.props.startTimer) {            this.startTimer()            this.setState({                timeLeft: this.props.fromStart            })        }    }    startTimer = () => {        var interval = setInterval(() => {            this.setState({                timeLeft: this.state.timeLeft - 1            })            if (this.state.timeLeft === 0) {                clearInterval(interval)            }        }, 1000)    }    render() {        return <Text style={globalStyles.testStyleThree}>{`00:${this.state.timeLeft > 9 ? this.state.timeLeft : `0${this.state.timeLeft}`}`}</Text>    }}
查看完整描述

3 回答

?
互換的青春

TA貢獻1797條經驗 獲得超6個贊

這就是使用React.memo的意義所在,以防止在子組件的 props 不變時重新渲染它們。


React.memo 是一個高階組件。它類似于 React.PureComponent 但用于函數組件而不是類。


如果你的函數組件在給定相同的 props 的情況下呈現相同的結果,你可以將它包裝在對 React.memo 的調用中,以便在某些情況下通過記憶結果來提高性能。這意味著 React 將跳過渲染組件,并重用上次渲染的結果。


    const FunctionalComponent = React.memo<{initialValue: number}>({initialValue}) => {

      const [timerValue, setTimerValue] = useState(initialValue)

    

      console.log('Set State')

    

      useEffect(() => {

          console.log('UseEffects called')

    

          setInterval(() => {

              setTimerValue(timerValue - 1)

          }, 1000)

    

      }, [])

    

      return <View><Text style={styles.textStyle}>{timerValue} 

 </Text></View>


    };


查看完整回答
反對 回復 2022-11-11
?
一只名叫tom的貓

TA貢獻1906條經驗 獲得超3個贊

出 React.memo,如果子組件的 props 沒有改變,女巫將阻止重新渲染

const FunctionalComponent = React.memo((props: any) => { .... } )



查看完整回答
反對 回復 2022-11-11
?
ibeautiful

TA貢獻1993條經驗 獲得超6個贊

人們建議useEffect但它會在渲染后被調用。


改用useMemo:


useMemo(() => {

  console.log('This is useMemo')

}, []);


查看完整回答
反對 回復 2022-11-11
  • 3 回答
  • 0 關注
  • 124 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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