React Native post文字字符串有效,但在发布状态变量时失败

时间:2016-06-14 15:26:05

标签: react-native

当我尝试将变量发布为:

时,它失败了
body: JSON.stringify({
  username: this.state.username, // it doesn't work, 
}),

但如果发布为:

,一切都很好
body: JSON.stringify({
  username: 'literal string', // it works well
}),

我可以从console.log中获取this.state.username的正确值,那么帖子上的问题是什么?这是完成的代码:

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  TextInput,
  TouchableOpacity,
} from 'react-native';

const REQUEST_URL = 'http://localhost:8000/user';

export default class AddAUser extends Component {
  constructor(props) {
    super(props);

    this.state = {
      username: null,
      submit: false,
    }
  }

  async _signup() {
    try {
      await this.setState({
        username: this.state.username,
        submit: true
      });

      let response = await fetch(REQUEST_URL, {
        method: 'POST',
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          username: this.state.username, // it doesn't work, 
          // username: console.log(this.state.username),  // get correct value from TextInput
          // username: 'literal string', // it works well
        }),
      });

      await console.log(response);

    } catch (error) {
      console.log(error);
    }
  }

  render() {
    return (
      <View style={styles.container}>
        <TextInput style={styles.textInputBox} placeholder='Username' value={this.state.username} onChangeText={(username) => this.setState({username: username})} />
        <TouchableOpacity
          style={styles.submitButton}
          onPress={() => this._signup()}
          >
          <Text>Sign Up</Text>
        </TouchableOpacity>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
  textInputBox: {
    height: 40,
    borderColor: 'lightblue',
    borderWidth: 1,
    borderRadius: 5,
    margin: 20,
    paddingLeft: 10,
  },
  submitButton: {
    marginTop: 20,
    paddingTop: 5,
    paddingBottom: 5,
    paddingLeft: 20,
    paddingRight: 20,
    backgroundColor: 'lightblue',
    borderRadius: 5,
  }
});

1 个答案:

答案 0 :(得分:1)

我不确定您使用async + await尝试实现的目标,但在上下文中没有解释。

我在没有他们的情况下尝试了:https://rnplay.org/apps/8U6_sA,它似乎像预期的那样工作。