【问题标题】:React native json parsing through Mysql通过 Mysql 反应原生 json 解析
【发布时间】:2019-09-30 22:07:52
【问题描述】:

我是 react-native 的新手。我需要将我的 JSON 显示到我的 react native 主页中,但我不知道该怎么做。你有什么建议,尤其是 Json 文件很长。我想在替代列表视图中仅显示 "s_title":"hjkjhjk","s_description":"jnkmjhnkl"

JSON

Array [
  Object {
    "fk_c_locale_code": "en_US",
    "fk_i_item_id": 3,
    "s_description": "jnkmjhnkl",
    "s_title": "hjkjhjk",
  },

我的主要 React-Native 页面如下,我需要它从 Json 文件中读取:

import {
  Button,
  Alert

} 
HomeScreen.navigationOptions = {
  header: null,
};

function test(){
  fetch('http://***:3000/users')
    .then(response => response.json())
    .then(users => console.warn(users));
  //Alert.alert(response);
}

【问题讨论】:

    标签: mysql json react-native parsing


    【解决方案1】:

    下面的代码有效。不需要解析什么的!

    来源是 react-native 页面的网络信息部分。

    
    import React, {Component} from 'react';
    import {Platform, StyleSheet, Text, View, FlatList} from 'react-native';
    
    const instructions = Platform.select({
      ios: 'Press Cmd+R to reload,\n' + 'Cmd+D or shake for dev menu',
      android:
        'Double tap R on your keyboard to reload,\n' +
        'Shake or press menu button for dev menu',
    });
    
    export default class App extends Component {
    
      constructor(props) {
        super(props);
        this.state = {
          dataSource:[]
         };
       }
    
      componentDidMount(){
        fetch("http://*****:3000/users")
        .then(response => response.json())
        .then((responseJson)=> {
          this.setState({
           dataSource: responseJson
          })
        })
        .catch(error=>console.log(error)) //to catch the errors if any
        }
    
        render(){
         return(
          <View style={{padding:10}}>
          <FlatList
          padding ={30}
             data={this.state.dataSource}
             renderItem={({item}) => 
             <View style={{height: 50}}>
             <Text style={{height: 50}}>{item.s_description}</Text>
             <Text style={{height: 50}}>{item.s_title}</Text>
             <View style={{height: 1,backgroundColor:'gray'}}></View>
             </View>
            }
           />
    
         </View>
         )}
    }
    

    【讨论】:

      【解决方案2】:

      最简单的方法是你的jsonobject[0].s_titlejsonobject[0].s_description

      在分配之前检查它是否未定义;类似:

      title = jsonobject[0].s_title === undefined ? "" : jsonobject[0].s_title
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-09-24
        • 1970-01-01
        • 1970-01-01
        • 2020-08-26
        • 1970-01-01
        • 1970-01-01
        • 2016-03-11
        • 2021-04-07
        相关资源
        最近更新 更多