在 React Native 中调用应用程序加载函数

Call function on application load in React Native

我有一个 React Native 应用程序,它有选项卡式布局。加载主屏幕时,我需要调用一些函数。我尝试使用 componentWillMount() 函数,但它不起作用,因为我的屏幕是在函数中定义的,而不是在 class 中定义的。如何创建加载函数?

HomeScreen.js

import React, { useState, Component } from 'react';
import { View, Text } from 'react-native';
import { getText } from '..components/getText';

export default function HomeScreen() {

  const [onLoadText, setText] = useState("");

  const onScreenLoad = () => {
    setText(getText());
  }

  const componentWillMount = () => {
    // Not working
    onScreenLoad();
  }

  return (
    <View style={styles.container}>
      <Text>{onLoadText}</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
  },
});

由于您使用的是无状态组件,因此可以使用 useEffect 挂钩

useEffect(() => {
// write your code here, it's like componentWillMount
}, [])

必须添加useEffect

import React, { useState, Component, useEffect } from 'react';
import { View, Text } from 'react-native';
import { getText } from '..components/getText';

export default function HomeScreen() {

    const [onLoadText, setText] = useState("");

    const onScreenLoad = () => {
        setText(getText());
    }
    useEffect(() => {
        // write your code here, it's like componentWillMount
        onScreenLoad();
    }, [])

    return (
        <View style={styles.container}>
            <Text>{onLoadText}</Text>
        </View>
    );
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#fff',
    },
});