我正在使用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>
);
}
}
答案 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");
}
});