【问题标题】:React Native Fetch works only on second clickReact Native Fetch 仅在第二次点击时有效
【发布时间】: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


【解决方案1】:

当 promise 解决时,你应该更新状态。

.then((responseData) => {
     this.setState({
       token: responseData.token
     });
   })

使用catch方法:

.then().catch(e => console.log("error: ", e))

另外,您的警报功能在哪里? react-native 有 Alert 模块。

Alert.alert('any message text');

关于fetch的文章

这是 article 在 react-native 中使用 fetch

【讨论】:

    【解决方案2】:

    另一个奇怪的事情是,当我第一次按下按钮时

    这很像与焦点有关。 尝试将keyboardShouldPersistTaps = true 设置为TouchableNativeFeedback

    【讨论】:

      猜你喜欢
      • 2017-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多