如何在钩子中渲染本机之前调用函数?

问题描述 投票:0回答:1

使用效果仅在渲染后运行。哪种方法只会调用一次并在函数钩子中的初始渲染之前运行?我不能使用componentWillMount,因为它必须在类component内,并且hook必须在function内。

react-native react-hooks lifecycle
1个回答
1
投票

实际上,钩子本身就是函数(它们使您可以使用状态和其他React功能)而无需编写类。而且它们各自没有任何组件生命周期方法,例如componentWillMount()等。

所以一种解决方案是将钩子用作类中的单独组件。然后在js类中,您可以访问所有生命周期方法。有一个方法shouldComponentUpdate(state,props)它带有道具和状态,您可以比较是否要重新渲染屏幕。它将在渲染之前立即调用。如果返回“ true”,则屏幕将再次渲染,否则不进行渲染。

shouldComponentUpdate(nextProps, nextState) {
if (nextProps === this.props && nextState === this.state)
  return false
else
  return true

}

下面是在类的render方法中使用钩子的示例

 import React, { useState } from 'react';
 const ExampleHook = props => {
   return (
      <View>
        <Text>Hello i am from hook</Text>
      </View>
    );
 }
 export default ExampleHook

现在您必须将此钩子导入其他js文件中。并且您可以在该类的render方法中使用它。您必须根据shouldComponentUpdate()函数的决定进行决定。

© www.soinside.com 2019 - 2024. All rights reserved.