我需要访问一个使用状态值的函数。以下是我当前实现的示例代码。
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函数中访问许多状态,什么是处理这种情况的最佳方法?
答案 0 :(得分:0)
如果将useEffect依赖项更改为“ name”变量,该怎么办:
useEffect(() => {
navigation.setParams({
onSave
});
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [name]);
有什么不同吗?