如何在我的方法中拥有反应绑定重置操作?



我正在使用 react-navigation 和 react-native。当我在render()内调用this.props.navigation.dispatch (resetAction)时。已经在里面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>
);
}
}

你必须将函数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");
} 
});

最新更新