访问在navigationOptions中的功能组件内部定义的功能

问题描述

我需要访问一个使用状态值的函数。以下是我当前实现的示例代码。

import React,{ useState,useEffect } from 'react';
import { View,Text,Button,TouchableOpacity } from 'react-native';
import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons';
import { withNavigationFocus } from 'react-navigation';

const HomeScreen = ({ navigation }) => {
    const [name,setName] = useState('');

    useEffect(() => {
        navigation.setParams({
            onSave
        });
        // eslint-disable-next-line react-hooks/exhaustive-deps
    },[onSave]);

    const onSave = () => {
        // name value will be used in this function
        console.log(name);
    };

    return (
        <View>
            <Text>{name}</Text>
            <Button title="Change name" onPress={() => setName('John')} />
        </View>
    );
};

HomeScreen.navigationOptions = ({ navigation }) => {
    const onSave = navigation.getParam('onSave',false);
    return {
        title: 'Home',headerRight: (
            <TouchableOpacity onPress={onSave}>
                <MaterialCommunityIcons name="content-save" color={'black'} />
            </TouchableOpacity>
        )
    };
};

export default withNavigationFocus(HomeScreen);

尽管可以访问onSave函数。我无法获取更新的“名称”状态。我知道我们可以在状态更改时重置onSave参数,但是如果需要在onSave函数中访问许多状态,什么是处理这种情况的最佳方法?

解决方法

如果将useEffect依赖项更改为“ name”变量,该怎么办:

useEffect(() => {
    navigation.setParams({
        onSave
    });
    // eslint-disable-next-line react-hooks/exhaustive-deps
},[name]);

有什么不同吗?

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...