下面是生成一系列按钮的代码。当初始呈现发生时,一个函数决定元素是否有一个名为init的支柱。如果它这样做了,它就会执行操作,就像单击了该按钮一样。
从技术上讲,这段代码可以工作,但它会触发一个警告,因为它有效地触发了渲染过程中的重呈现。如何触发有效的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>
);
}
}发布于 2020-02-27 14:06:46
警告是由对仍在呈现的组件执行函数引起的,尽管它在技术上有效,但解决方案与问题是一致的。
有许多内置的函数,包括满足有效onRender要求的函数。
从呈现中移除脚本,并将其置于componentDidMount()函数中的render之上。
componentDidMount() {
if(this.props.init){
this.NavTabAction()
}
}QED
发布于 2020-02-27 14:09:02
对于基于类的React组件,如在您的示例中,您将使用componentDidMount()生命周期方法,该方法只在组件加载之后触发一次,例如:
componentDidMount(){
this.NavTabAction();
}尽管如此,我还是鼓励您使用反应钩,因为React世界正在从基于类的组件转向功能组件+挂钩。
要用钩子实现类似的componentDidMount功能,您可以在一个功能组件中使用如下useEffect:
useEffect(() => {
this.NavTabAction();
}, []); // the [] is important here to behave similar to componentDidMount.https://stackoverflow.com/questions/60434706
复制相似问题