我该如何发送带有参数和获取响应的发布请求-React Native

时间:2019-07-14 10:29:13

标签: api react-native react-native-android

我想使用输入文本中的参数将请求发送到服务器,并在新页面上获取响应,我尝试了许多教程,但没有一个起作用。我尝试过

  constructor() {
    super();
      this.state={
        username:'',
        password:'',
        kode_ujian:''
      }
  }

  updateValue(text, field) {
    if(field=='username')
    {
      this.setState({
        username:text,
      })
    }
    else if(field=='password')
    {
      this.setState({
        password:text,
      })
    }
    else if(field=='kode_ujian')
    {
      this.setState({
        kode_ujian:text,
      })
    }
  }

还有这个

submit() {
    let collection={}
    collection.username=this.state.username,
    collection.email=this.state.password,
    collection.kode_ujian=this.state.kode_ujian

    fetch('https://ffst.my.id/onclass/index.php/api/list_jawaban', {
      method: 'POST',
      headers: {
        Accept: 'text/html',
        'Content-Type': 'text/html',
      },
      body: JSON.stringify({
        username: 'this.state.username',
        password: 'this.state.password',
        kode_ujian: 'this.state.kode_ujian'
      })
      .then((response) => response.text())
      .then((text) => {
        return text;
        console.warn(text);
      })
    });
  }


render() {

    return(
        <View style={styles.container}>
              <TextInput style={styles.inputBox}underlineColorAndroid='rgba(0,0,0,0)' onChangeText={(text) => this.updateValue(text, 'username')}
                placeholder="Username" placeholderTextColor = "#ffffff"/>
              <TextInput style={styles.inputBox}underlineColorAndroid='rgba(0,0,0,0)' onChangeText={(text) => this.updateValue(text, 'password')}
                placeholder="Password" placeholderTextColor = "#ffffff" secureTextEntry={true}/>
              <TextInput style={styles.inputBox}underlineColorAndroid='rgba(0,0,0,0)' onChangeText={(text) => this.updateValue(text, 'kode_ujian')}
                placeholder="Kode Ujian" placeholderTextColor = "#ffffff"/>
              <TouchableOpacity onPress={()=>this.submit()} style={styles.button}>
              <Text style={styles.buttonText}>Submit</Text>
              </TouchableOpacity>
                </View>
                        );
  }
}

第一个代码是我之前尝试过的代码,第二个代码是我的输入文本,有解决方案吗?

2 个答案:

答案 0 :(得分:0)

这是带有axios的Post Request`示例:

import React from 'react';
import axios from 'axios';

export default class PersonList extends React.Component {
  state = {
    name: '',
  }

  handleChange = event => {
    this.setState({ name: event.target.value });
  }

  handleSubmit = event => {
    event.preventDefault();

    const user = {
      name: this.state.name
    };

    axios.post(`https://jsonplaceholder.typicode.com/users`, { user })
      .then(res => {
        console.log(res);
        console.log(res.data);
      })
  }

  render() {
    return (
      <div>
        <form onSubmit={this.handleSubmit}>
          <label>
            Person Name:
            <input type="text" name="name" onChange={this.handleChange} />
          </label>
          <button type="submit">Add</button>
        </form>
      </div>
    )
  }
}

还有一个fetch的示例:

// App.js
import React, { Component } from ‘react’;
import ‘./App.css’;

export default class App extends Component{
    constructor(){
        super();
        this.state={ name:’’, email:’’ }
    }
    handleChange = event =>{
        this.setState({ [event.target.name]:event.target.value })
    }
    handleSubmit = event =>{
        event.preventDefault();
        console.log(“User name : “ + this.state.name)
        console.log(“User Email : “ + this.state.email)
        const url =”https://jsonplaceholder.typicode.com/users/”
            const data = { name:this.state.name, email:this.state.email }
        fetch(url, { method: ‘POST’, // or ‘PUT’
        body: JSON.stringify(data), // data can be `string` or {object}!
            headers:{ ‘Content-Type’: ‘application/json’ } })
    .then(res => res.json())
            .catch(error => console.error(‘Error:’, error))
    .then(response => console.log(‘Success:’, response)); }
    render(){
        return(
            <form onSubmit={this.handleSubmit}>
                <input type=”text” name=”name” onChange={this.handleChange} />
                <input type=”email” name=”email” onChange={this.handleChange} />
                <input type=”submit” value=”Add user” /> 
            </form> 
        )
    }
}

答案 1 :(得分:0)

我注意到了可能引起问题的两个方面。

首先,在创建主体时,将状态变量封装在引号中,这意味着它将使用字符串“ this.state.username”而不是其表示的变量。尝试像这样设置您的身体:

body: JSON.stringify({
    username: this.state.username,
    password: this.state.password,
    kode_ujian: this.state.kode_ujian
})

第二,您将.then语句放置在JSON.stringify之后,该语句不返回承诺。将您的.then语句移至fetch查询的末尾,这将正确地传递响应。目前,即使由于.then处理程序语句的错误位置而正确获取了您的响应,也根本无法处理结果。

如果您将submit方法更改为此,则它应该可以正常工作。

submit() {
  let collection={}
  collection.username=this.state.username,
  collection.email=this.state.password,
  collection.kode_ujian=this.state.kode_ujian

  fetch('https://ffst.my.id/onclass/index.php/api/list_jawaban', {
    method: 'POST',
    headers: {
      Accept: 'text/html',
      'Content-Type': 'text/html',
    },
    body: JSON.stringify({
      username: this.state.username,
      password: this.state.password,
      kode_ujian: this.state.kode_ujian
    })
  })
  .then((response) => response.json())
  .then((json) => {
    console.log(json);
    return json;
  })
}

我还将response.text()更改为response.json(),这会将其转换为JS对象,并使访问结果更加容易。

然后,作为单独的注释,您的updateValue函数可以大大简化为以下函数:

updateValue(text, field) {
    this.setState({ [field]: value });
}