簡體   English   中英

在 React Native 中執行 OnRender 函數

[英]Perform a function OnRender in React Native

以下是生成一系列按鈕的代碼。 當初始渲染發生時,一個函數確定元素是否有一個名為 init 的 prop。 如果這樣做,它會執行操作,就好像該按鈕已被單擊一樣。

從技術上講,此代碼有效,但會觸發警告,因為它可以有效地在渲染過程中觸發重新渲染。 如何觸發有效的 OnRender 函數?

export class NavTabItem extends React.Component {
    constructor(props) {
        super(props);
        global.register(this, 'screen')
    }

    NavTabAction = () => {
        global.setState({
            screen: this.props.screen,
        })
    }

    render() {

// determine whether the element has the prop of init and if it does click on it.

        if(this.props.init){
            this.NavTabAction()
        }

        return (
            <TouchableOpacity onPress={this.NavTabAction}>
                <View style={global.state.screen == this.props.screen ? [styles.NavTabItem, styles.NavTabItemSelected] : styles.NavTabItem}>
                    <View style={styles.NavTabIcon} />
                    <TextCap11 style={styles.NavTabLabel}>{this.props.children}</TextCap11>
                </View>
            </TouchableOpacity>
     );
  }
}

對於基於類的 React 組件,例如在您的示例中,您將使用componentDidMount()生命周期方法,該方法僅在組件加載后觸發一次,例如:

componentDidMount(){
  this.NavTabAction();
}

也就是說,我鼓勵你使用React Hooks ,因為 React 世界正在從基於類的組件轉向功能組件 + 鈎子。

要使用鈎子實現類似的 componentDidMount 功能,您可以在功能組件中像這樣使用useEffect

useEffect(() => {
  this.NavTabAction();
}, []);  // the [] is important here to behave similar to componentDidMount.

警告是由於在仍在渲染的組件上執行功能引起的,盡管它在技術上有效,但解決方案符合問題。

有許多內置函數,包括滿足有效 onRender 要求的函數。

從渲染中移除腳本並將其放置在 componentDidMount() 函數內的渲染之上。

componentDidMount() {
        if(this.props.init){
            this.NavTabAction()
        }
    }

QED

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM