【发布时间】:2016-06-02 13:48:03
【问题描述】:
我在 React Native 上做应用。接下来是问题:
OnPress 我正在尝试向我的服务器发出请求并记录答案的某些元素。
当我第一次单击按钮时 - 我的日志不显示任何内容,但在第二次单击时我会在控制台中看到响应。
import React from 'react'
import { View, Text, StyleSheet, TextInput , TouchableNativeFeedback , AsyncStorage } from 'react-native'
import {connect} from 'react-redux'
import * as pageActions from '../action/index'
import { bindActionCreators } from 'redux'
import api from '../api'
class Login extends React.Component {
constructor(props){
super(props);
this.state = {
loginAttempt : false,
email : 'admin@mail.ru',
password : 'password',
token : ''
}
}
loginAttempt() {
let email = this.state.email;
let password = this.state.password;
api.login(email,password)
}
render() {
return (
<View style={styles.container}>
<TextInput
placeholder="Email"
style={{height: 50, borderColor: 'gray', borderWidth: 1}}
onChangeText={(value) => this.setState({email : value})}
/>
<TextInput
placeholder="Password"
style={{height: 50, borderColor: 'gray', borderWidth: 1}}
onChangeText={(value) => this.setState({password : value})}
/>
<TouchableNativeFeedback
style={!this.state.loginAttempt ? {'opacity' : 1} : {'opacity' : 0}}
onPress={() => this.loginAttempt()}>
<View>
<Text>Try login</Text>
</View>
</TouchableNativeFeedback>
</View>
)
}
}
var styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center'
}
}
)
我的获取函数
login(email,password, callback) {
const API_HEADERS = {
'Accept' : `application/json`,
'Content-Type' : `application/json`
};
let user = {};
user.email = email;
user.password = password;
fetch(`http://myIp:3000/auth/login`, {
method : 'post',
headers : API_HEADERS,
body : JSON.stringify(user)
})
.then((response) => {
if (response.ok) {
return response.json();
} else {
alert(`Wrong data`)
}
})
.then((responseData) => {
console.log(responseData)
})
}
还想补充一点,我使用 Genymotion 作为 android emul。另一个奇怪的事情是,当我第一次按下按钮时 - 没有任何反应,但是当我按下 Reload JS 时,在卸载组件之前,我看到我的 responceData 在控制台
【问题讨论】:
-
我遇到了这个问题,你解决了吗?
标签: reactjs react-native fetch