【问题标题】:Perform a function OnRender in React Native在 React Native 中执行函数 OnRender
【发布时间】:2020-06-11 13:16:48
【问题描述】:

以下是生成一系列按钮的代码。当初始渲染发生时,一个函数确定元素是否有一个名为 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>
     );
  }
}

【问题讨论】:

    标签: function react-native render


    【解决方案1】:

    对于基于类的 React 组件,例如在您的示例中,您将使用 componentDidMount() 生命周期方法,该方法仅在组件加载后触发一次,例如:

    componentDidMount(){
      this.NavTabAction();
    }
    

    也就是说,我鼓励你使用React Hooks,因为 React 世界正在从基于类的组件转向函数式组件 + 钩子。

    要使用钩子实现类似的 componentDidMount 功能,您可以在 functional 组件中像这样使用useEffect

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

    【讨论】:

    • 看起来值得进一步了解。直接复制你的 useEffect 会导致错误。我是否认为在使用它之前还有更多需要了解的内容?
    • 是的,您需要将组件重构为功能组件。 effect hooks 文档中的第一个示例是一个很好的开始(如果您需要在其他地方导入该函数,请不要忘记导出该函数)。不过,我强烈建议您阅读React Hooks docs,以获得良好的基础。祝你好运!
    【解决方案2】:

    警告是由对仍在渲染的组件执行功能引起的,虽然它在技术上有效,但解决方案符合问题。

    有许多内置函数,其中一个可以满足有效 onRender 的要求。

    从渲染中移除脚本并将其放置在 componentDidMount() 函数内的渲染之上。

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

    QED

    【讨论】:

      猜你喜欢
      • 2016-09-10
      • 2022-06-15
      • 1970-01-01
      • 1970-01-01
      • 2018-09-02
      • 2021-08-01
      • 2017-10-28
      • 1970-01-01
      • 2019-10-11
      相关资源
      最近更新 更多