我按下按钮时未调用方法

时间:2019-08-30 11:09:47

标签: react-native react-redux react-navigation redux-thunk react-navigation-stack

我正在使用反应导航,并在右侧添加了一个按钮,使用默认导航选项从我的应用注销,如下所示:

const otherApp = createStackNavigator({
  Welcome : { 
    screen : WelcomeScreen
  }
},
{
  defaultNavigationOptions : ({navigation}) => ({
    title : 'Welcome',
    headerStyle: {
      backgroundColor: '#29434e',
      shadowColor: 'transparent',
      elevation: 0
    },
    headerRight: (
      <TouchableOpacity
        style={{ backgroundColor: '#DDDDDD', padding: 5 }}
        onPress={() => navigation.getParam('logout')}>
        <Text
          style={{
            fontSize: 10,
          }}>
          Logout
        </Text>
      </TouchableOpacity>
    ),
  })
});

我正在绑定要调用的方法,如下所示:

_Logout() {
    this.props.signOut();
  }
  componentDidMount(){
    this.props.navigation.setParams({ logout : this._Logout.bind(this) })
  }

使用redux将功能映射到道具

const mapDispatchToProps = (dispatch) => {
  return {
    Signout : ()=> dispatch(Signout())
  }
}

但是问题是当我按下按钮时,它没有调用方法!

2 个答案:

答案 0 :(得分:0)

您还可以使用onFocus的{​​{1}}方法来查看屏幕是否对焦。如果屏幕对准焦点,则调用该函数。

react-navigation

方法:2

import { withNavigation } from "react-navigation";
 componentDidMount() {
    const { navigation } = this.props;
    this.focusListener = navigation.addListener("didFocus", () => {
      // The screen is focused
      // Call any action
    });
  }

  componentWillUnmount() {
    // Remove the event listener
    this.focusListener.remove();
  }

export default withNavigation(Your Class Name);

答案 1 :(得分:0)

我得到了解决方案,我做错了什么,因为我没有在按钮的onPress上传递回电话!

logoutFromFirebase = () => {
    this.props.Signout();
    this.props.navigation.navigate(this.props.user.uid ? 'App' : 'Auth')
  }
  componentDidMount(){
    this.props.navigation.setParams({ logout : this.logoutFromFirebase })
  }

默认导航

defaultNavigationOptions : ({navigation}) => ({
    title : 'Welcome',
    headerStyle: {
      backgroundColor: '#29434e',
      shadowColor: 'transparent',
      elevation: 0
    },
    headerRight: (
      <TouchableOpacity
        style={{ backgroundColor: '#DDDDDD', padding: 5 }}
        onPress={navigation.getParam('logout' , () => Reactotron.log('Logout not callled'))}>
        <Text
          style={{
            fontSize: 10,
          }}>
          Logout
        </Text>
      </TouchableOpacity>
    ),
  })

现在一切正常!