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

时间:2019-10-28 03:23:42

标签: react-native react-hooks lifecycle

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

1 个答案:

答案 0 :(得分: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()函数的决定进行决定。

相关问题