如何在我的方法中使用react bind resetAction?

时间:2017-09-03 15:44:15

标签: javascript reactjs react-native react-navigation

我正在使用react-navigation和react-native。当我在this.props.navigation.dispatch (resetAction)内部调用render()时。已经在Buttonpress()内了。我的目标是在Parse Server对用户进行身份验证并重置路由时转到另一条路由。

自动翻译。

import React, {Component} from 'react';
import {Container, Content, Form, Item, Input, Button, Text} from 'native-base';
var Parse = require('parse/react-native');

import {NavigationActions} from 'react-navigation'

const resetAction = NavigationActions.reset({
  index: 0,
  actions: [NavigationActions.navigate({routeName: 'Main'})]
})

export default class Auth extends Component {
  constructor(props) {
    super(props);
    this.state = {
      username: '',
      password: ''
    };
    this.Buttonpress = this.Buttonpress.bind(this);
  }
  static navigationOptions = {
    title: 'Hedone'
  };

  Buttonpress() {
    Parse.initialize("APPLICATION_ID");
    Parse.serverURL = 'http://192.168.25.18:1337/parse'

    Parse.User.logIn(this.state.username, this.state.password, {
      success: function(user) {
        // Do stuff after successful login.
        () => this.props.navigation.dispatch(resetAction)
        console.warn("Certo")
      },
      error: function(user, error) {
        // The login failed. Check error to see why.
        console.warn("Errado");
      }
    });
  }

  render() {
    const {navigate} = this.props.navigation;
    return (
      <Container>
        <Content>
          <Form>
            <Item>
              <Input placeholder="Username" onChangeText={(text) => this.setState({username: text})}/>
            </Item>
            <Item last>
              <Input placeholder="Password" onChangeText={(text) => this.setState({password: text})}/>
            </Item>
          </Form>

          <Button block onPress={this.Buttonpress}>
            <Text>Entrar</Text>
          </Button>

          <Button block onPress={() => navigate('Up')}>
            <Text>Inscrever-se</Text>
          </Button>
        </Content>
      </Container>
    );
  }
}

1 个答案:

答案 0 :(得分:1)

你必须bind你的函数到当前上下文,因为它将从this != this的其他地方调用,因为它在另一个上下文中。如果要使用当前this上下文中的某些变量/函数,则只需执行此操作。

Parse.User.logIn(this.state.username, this.state.password, {
    // needs to be bind because you want use 
    // `this.props` from the current context
    success: function (user) {
        // Do stuff after successful login.
        this.props.navigation.dispatch(resetAction)
        console.warn("Certo")
    }.bind(this),
    // this doesn't need to be bind, because it 
    // doesn't use something from this context
    error: function (user, error) {
        // The login failed. Check error to see why.
        console.warn("Errado");
    } 
});