在React native中变得未定义

时间:2018-10-23 13:10:45

标签: react-native react-native-android

import React, { Component } from 'react';
import { View, Text } from 'react-native';

class HttpExample extends Component {
   state = {
      data: ''
   }
   componentDidMount = () => {
    fetch("https://jsonplaceholder.typicode.com/posts/1", { --this is fake url 
        method: 'POST',
        headers: new Headers({
                   'Content-Type': 'application/x-www-form-urlencoded', // <-- Specifying the Content-Type
          }),
        body: "param1=value1&param2=value2" // <-- Post parameters
      })
      .then((response) => 
          response.text()
      )
      .then((responseText) => {
        alert(responseText.id);
        this.setState({
            data: responseText
         })
      })
      .catch((error) => {
          console.error(error);
      });
   }
   render() {
      return (
         <View>
            <Text>
               {this.state.data.id}
            </Text>
         </View>
      )
   }
}
export default HttpExample;

如果我使用alert(ResponseText) 在警报中,我得到o / p,但是由于我尝试从对象中获取单独的值,因此返回undefined

o / p:“ id”:“ 1”,     “ computeId”:警报中为“ USR00001”

1 个答案:

答案 0 :(得分:0)

 .then((response) => response.text())

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

我想您需要JSON样式响应。