【问题标题】:Displaying JSON format response into React-Native将 JSON 格式响应显示到 React-Native
【发布时间】:2018-03-28 13:34:53
【问题描述】:

我通过 API 向服务器发送了一个 post 请求,我收到以下 JSON 格式的响应(console.log 屏幕截图):

执行以下代码后,我能够在警报对话框中显示响应:

uploadPhoto() {
  RNFetchBlob.fetch('POST', 'http://192.168.1.102:8000/api/v1/reader/', {
    Authorization: 'Bearer access-token',
    otherHeader: 'foo',
    'Content-Type': 'multipart/form-data',
  }, [
    { name: 'image', filename: 'image.png', type: 'image/png', data: this.state.data },
  ]).then((response) => response.json())
         .then((responseJson) => {
           this.setState({
             jsonData: responseJson
           }, () => {
             Alert.alert(" Vehicle Number Plate:  " + responseJson.processed_text);
            console.log(responseJson);
           });
         })
         .catch((error) => {
           console.error(error);
         });
}
<TouchableOpacity
 style={styles.buttonStyle} 
 onPress={this.uploadPhoto.bind(this)}>
<Text style={styles.btnTextStyle}> Process Image</Text>
</TouchableOpacity>

但是,由于我对 React-Native 开发非常陌生,因此除了在警报对话框中之外,我无法在应用程序中显示 JSON 数据。以下是我的代码:

通过构造函数初始化jsonData对象的状态:

constructor() {
      super();
      this.state = {
        imageSource: null,
        data: null,
        jsonData: []
      };
  }

然后,设置jsonData对象的状态(详细:上面的代码sn-p):

.then((response) => response.json())
         .then((responseJson) => {
           this.setState({
             jsonData: responseJson
           }

最后,我使用了组件 FlatList 来显示数据:

<View>
   <Text>Display Response JSON Data</Text>
   <FlatList
   data={this.state.jsonData}
   renderItem={({ item }) => <Text> {item.processed_text } </Text>}
   />
</View>

但是,我看不到输出!我该如何解决这个问题?

【问题讨论】:

  • 尝试在 then 中放置一个 console.log 并打印您的组件实际看到的内容。或者覆盖 componentDidUpdate(prevProps, prevState) 并打印变量
  • @Sarun 如果您在此行下方添加console.log(responseJson) .then((responseJson),它将对我们有所帮助。
  • ...或者我需要比获取更好的东西。尝试使用axiosgithub.com/axios/axios
  • FlatList 组件需要一个数组。我假设你的响应是一个对象而不是一个数组

标签: json react-native react-native-android react-native-flatlist react-native-listview


【解决方案1】:

Flatlist 适用于数组。您的响应应该是这样的数组:

[
 { processed_text: 'value1', owner: { fullname: 'alex' } },
 { processed_text: 'value2', owner: { fullname: 'john' } },
]

更多见解请查看Flatlist

【讨论】:

    猜你喜欢
    • 2018-03-16
    • 1970-01-01
    • 2018-01-16
    • 1970-01-01
    • 2015-08-13
    • 1970-01-01
    • 1970-01-01
    • 2017-12-15
    • 1970-01-01
    相关资源
    最近更新 更多