使用fetch React Native时,文本输入onSubmit

时间:2018-05-14 06:56:08

标签: javascript react-native

我正在尝试通过textInput更新我的昵称和电子邮件状态,然后通过发布请求将其提交给我的服务器。两者都不确定地回来了。我总是迷失在这里我做错了什么。

export default class Add extends Component {
  constructor(props){
    super(props);
    this.state ={ 
      isLoading: true,
      nickname: "",
      email: ""
    }
  }

  static navigationOptions = {
    title: 'Add Contacts',
  };

  componentDidMount(){
        this.setState({
          isLoading: false
        })
  }

  onSubmit = () => {
    console.log('on submit')
    return fetch(`...`, {
          method: 'POST',
          headers: {
            'Accept': 'application/json, text/plain */*',
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(this.state)    
        })
        .then((response) => response)
        .then((responseJson) => {
          return responseJson
        })
        .catch((error) => {
          throw error;
        })
  }

  render() {
    const { navigate } = this.props.navigation;
    if(this.state.isLoading){
      return(
        <View style={{flex: 1, padding: 20}}>
          <ActivityIndicator/>
        </View>
      )
    }
    return(
      <View 
        style={styles.container}
      >
        <Text 
          style={{fontSize:30}}>
          New Contact
        </Text>
            <View>
              <TextInput 
                ref= {(el) => { this.nickname = el; }} 
                onChangeText={(nickname) => this.setState({nickname}, function () {console.log('Nickname updated')})}
                value={this.state.nickname}
              />
              <TextInput 
                value={this.state.email}
                onChangeText={(text) => this.setState({email: text})}   
                />
            </View>
        <Button
          text = {
            <Text 
              style={{color:colors.textColor, textAlign: 'center'}}
              > 
              Save 
            </Text>
          } 
          onPress= { () => {
              this.onSubmit()
              navigate('Home')
           }
          }
        />
      </View>
    );
  }
}
const styles = StyleSheet.create({
  container: {
    marginTop: 20,
    alignItems: 'center',
    justifyContent: 'center',
  }
});

1 个答案:

答案 0 :(得分:1)

.then((response) => response)

应该是:

.then((response) => response.json())

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#Making_fetch_requests