【问题标题】:Access a function which is defined inside a functional component in navigationOptions访问在 navigationOptions 的功能组件内定义的功能
【发布时间】:2020-12-06 12:14:18
【问题描述】:

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

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 函数中访问许多状态,那么处理这种情况的最佳方法是什么?

【问题讨论】:

    标签: react-native state hook react-functional-component


    【解决方案1】:

    如果将 useEffect 依赖项更改为 'name' 变量会怎样:

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

    有影响吗?

    【讨论】:

    • 感谢您的回答。正如我在问题中提到的那样,这是处理它的最佳方法吗?如果我们有大约 10 个状态值要在 onSave 函数中访问,我们需要设置太多的值作为依赖项。
    • 我明白了.. 如果您删除所有依赖项会怎样。像这样:“useEffect(() => {...});”
    猜你喜欢
    • 2019-12-29
    • 1970-01-01
    • 2021-06-14
    • 2021-07-11
    • 2020-12-10
    • 1970-01-01
    • 2021-08-06
    • 2018-08-09
    • 2013-05-07
    相关资源
    最近更新 更多