【发布时间】: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