如何使用useEffect挂钩中定义的onPress(单击时)调用函数

时间:2020-07-05 14:25:39

标签: reactjs react-native react-hooks

我有一个注销屏幕,其中我定义了注销按钮,通过按注销按钮,我要删除令牌,并想重定向到登录屏幕,当我按此按钮时,它要删除令牌但不重定向到登录,当我关闭或关闭时将重定向重新打开或刷新后。 为了克服这个问题,我使用useEffect hook进行compnentDidUpdate或类似的操作。

useEffect(() => {
 const handleLogout = () => {
  // dispatch(logoutAction());
};
handleLogout();
}, [handleLogout]);

但是当我在onPress上调用handleLogout时,发生错误,未定义变量handleLogout,因为作用域无法在其作用域之外使用变量。

 <TouchableNativeFeedback onPress={handleLogout}>
    <View style={styles.logoutBtn}>
      <Text style={{color: '#FFFFFF'}}>Logout</Text>
    </View>
  </TouchableNativeFeedback>

2 个答案:

答案 0 :(得分:1)

只需在使用效果之外定义此函数,然后仅在useEffect内引用并调用它即可。

...
const handleLogout = () => {
  // dispatch(logoutAction());
};

useEffect(() => {
    handleLogout();
}, [handleLogout]);

return (
    <TouchableNativeFeedback onPress={handleLogout}>
    <View style={styles.logoutBtn}>
      <Text style={{color: '#FFFFFF'}}>Logout</Text>
    </View>
  </TouchableNativeFeedback>
)
...

但是我不确定这是否是“好的”做法,因为这可能会导致渲染上的useEffect触发器,因为您正在传递函数作为依赖项。因此,从我的观点来看,这看起来很奇怪。我该怎么做,将useEffect丢掉,然后尝试在分派中添加一些额外的功能。像

...
const navigation = useNavigation()

const handleLogout = () => {
  dispatch(logoutAction());
  navigation.navigate('YourInitialScreen')
};

return (
    <TouchableNativeFeedback onPress={handleLogout}>
    <View style={styles.logoutBtn}>
      <Text style={{color: '#FFFFFF'}}>Logout</Text>
    </View>
  </TouchableNativeFeedback>
)
...

在不知道dispatch真正做什么的情况下,很难理解您到底想做什么。但这可能有助于您进行头脑风暴。

答案 1 :(得分:0)

将函数定义移至useEffect之外:

const handleLogout = () => {
  // dispatch(logoutAction());
};

useEffect(() => {
  handleLogout();
}, [handleLogout]);
相关问题