使用Fetch传递参数并在react native中显示响应?

时间:2018-08-01 21:58:12

标签: javascript reactjs fetch

我想将用户名和密码传递给API。我的代码允许用户登录,API可以根据用户是否存在来检查或拒绝该请求。

但是,我要进行响应并在下一个屏幕上显示用户名。我该如何处理?

以下是返回的响应(如果登录成功):

{
  "data": {
    "user": {
      "name": "Test One",
      "email": "testuser1@gmail.com",
      "username": "testuser1",
      "token": "3uio42h34b398r2h",
      "avatar": "/images/default.png"
    }
  }
}

这是我的源代码:

import React, { Component } from "react";
import {
  Platform,
  StyleSheet,
  Text,
  View,
  TextInput,
  Button
} from "react-native";

export default class LoginForm extends Component<{}> {
  constructor(props) {
    super(props);
    this._onLogInPressed = this._onLogInPressed.bind(this);
    this._response_recognizer = this._response_recognizer.bind(this);
    this.state = {
      phone_number: "",
      password: "",
      data: {}
    };
  }
  _response_recognizer(data: string) {}

  _onLogInPressed = () => {
    var data = {
      phone_number: this.state.phone_number,
      password: this.state.password
    };

    fetch("http://192.168.1.12:5000/login", {
      method: "POST",
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json"
      },
      body: JSON.stringify({
        email: this.state.email
      })
    })
      .then(response => response.json())

      .then(res => {
        console.log(res);

        if (res.status == 200) {
          this.props.navigation.navigate("Login");
          alert("Check your email for a password reset link!");
        } else if (res.status != 200) {
          alert("Email does not exist in our system.");
        }
      })
      .done();
  };

  render() {
    return (
      <View style={styles.flow}>
        <Text style={styles.text}>phone number:</Text>
        <TextInput
          keyboardType="numeric"
          style={styles.input}
          ref="phone_number"
          onChangeText={phone_number => this.setState({ phone_number })}
          maxLengt={11}
          value={this.state.phone_number}
        />
        <Text style={styles.text}>password:</Text>
        <TextInput
          style={styles.input}
          secureTextEntry={true}
          ref="password"
          onChangeText={password => this.setState({ password })}
          value={this.state.password}
        />
        <Button
          style={styles.button}
          onPress={this._onLogInPressed}
          title="login"
        />
      </View>
    );
  }
}

1 个答案:

答案 0 :(得分:0)

/* --------- Define 'name' in state ---------*/

 state = {
    name: ''
 }

/*------- if you will get success response then write this  -------*/ 

LoginAPICall = () => {
fetch(‘URL’, {
method: 'POST',
headers: {
  'Accept': 'application/json',
  'Content-Type': 'application/json',
},
body: JSON.stringify({
  Email: this.state.email,
  Password: this.state.password
})
}).then((response) => response.json())
  .then((responseJson) => {
 if(responseJson.statuscode == 1) {
  this.props.navigation.navigate(‘Login’,{
            NAME : responseJson['data']['user'].name
    });
  alert("Check your email for a password reset link!");      
} else {
  Alert.alert(responseJson.message);
}
}).catch((error) => {
  console.error(error);
});
}


/*--------- in next activity controller write below lines ---------*/

    constructor(){
    super();
    this.state = {
         User_Name : '',
    }
}

componentDidMount(){
    this.setState({
        User_Name: this.props.navigation.state.params.NAME,
    })
}

render () {
  alert (this.state.User_Name);
  return (
    <View>
        <Text>Hello</Text>
    </View>
  );
}