如何从我的 react-native redux 应用程序中的组件方法获取对调度方法的引用

How to get reference to the dispatch method from a component method in my react-native redux app

在我的 react-native 应用程序中,我正在尝试使用 redux connect 连接一个登录按钮。当我尝试触发 handleLogin 函数时,handleLogin 函数中的 this 似乎绑定到按钮,而不是组件。构建此方法的最佳方式是什么。我可以将调度函数作为参数传递给 handleLogin 但是有没有更简洁的方法从函数内部获取调度引用?

class Profile extends Component {

  handleLogin() {
    // wrong `this`, this.props is null and this refers to the button, not the component
    this.props.dispatch(login);
  }

  handleLogout() {
    this.props.dispatch(logout);
  }

  render() {
    const { dispatch, isAuthenticated, errorMessage, username } = this.props;
    return (
      <View style={styles.outer}>
        { isAuthenticated ? (
          <Button style={{ backgroundColor: 'red' }} textStyle={{ fontSize: 18 }} onPress={() => dispatch(logout)} >
            Logout {username}
          </Button>
        ) : (
          <Button style={{ backgroundColor: 'green' }} textStyle={{ fontSize: 18 }} onPress={this.handleLogin(dispatch)} >
            Login
          </Button>
        )}
      </View>
    );
  }

};

我假设我的连接方法会自动将调度连接到我的组件道具。

Profile.propTypes = {
  dispatch: PropTypes.func.isRequired,
  username: PropTypes.string,
  photo: PropTypes.string,
  isAuthenticated: PropTypes.bool.isRequired,
  errorMessage: PropTypes.string,
};

function mapStateToProps(state) {
  const { user } = state;
  const { isAuthenticated, errorMessage, photo, username } = user;
  return {
    username,
    photo,
    isAuthenticated,
    errorMessage,
  };
}

export default connect(mapStateToProps)(Profile);

尝试将方法正确绑定到内联回调时,您可以选择:

此外:您假设省略 mapDispatchToProps 结果 dispatch 被映射到道具 this.props.dispatch 是正确的.


使用箭头函数:

onPress={this.handleLogin(dispatch)}

至:

onPress={() => this.handleLogin}

// this 在箭头函数中词法绑定,耶!


在构造函数中使用bind:

constructor(props){
  super(props)

  this.handleLogin = this.handleLogin.bind(this);
}

在内联回调中使用bind:

onPress={this.handleLogin.bind(this);}