React Native如何存储和处理JSON数据?

时间:2019-07-29 03:22:21

标签: json react-native

我是React Native编程的初学者。我在查找说明如何执行此操作的教程时遇到了困难。

我正在从Web API获取公交时刻表数据。

我想做以下事情。

  1. 将JSON数据存储在变量或其他内容中。
  2. 在该JSON数据上运行函数以返回适当的总线数据

对此我有两个问题。

  1. 如何将JSON数据存储在变量内或以某种方式本地存储?
  2. 如果要对JSON数据运行JavaScript函数,该在哪里做?在单独的组件的render()函数内部?

我尝试过的

我在课堂外声明了let jsondata。 在componentDidMount内部,我使用匿名函数将responseJson存储到jsondata。当我在console.log上登录时,它会正确显示JSON数据。

但是,当我尝试在{console.log(jsondata)}之后尝试Flatlist时,它会返回undefined,而"Hello"会正确记录。

为什么会这样?如何使用jsondata?

代码

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

let jsondata;
export default class FetchExample extends React.Component {

    constructor(props){
        super(props);
        this.state ={ isLoading: true}

    }

    // make an API call in the beginning
    componentDidMount(){
        return fetch('https://api.myjson.com/bins/18o9sd')
            .then((response) => response.json())
            .then((responseJson) => {
                this.setState({
                    isLoading: false,
                    dataSource: responseJson.shosfc.weekday[7]
                }, function(){
                    jsondata = responseJson;
                    // console.log(jsondata)
                });

            })
            .catch((error) =>{
                console.error(error);
            });
    }

    render(){
        if(this.state.isLoading){
            return(
                <View style={{flex: 1, padding: 50}}>
                    <ActivityIndicator/>
                </View>
            )
        }

        return(
            <View style={{flex: 1, paddingTop:50}}>
                <FlatList
                    data={this.state.dataSource}
                    renderItem={({item}) => <Text>{item.min}</Text>}
                    // keyExtractor={({id}, index) => id}

                />
                {console.log(jsondata)}
            </View>

        );
    }
}

2 个答案:

答案 0 :(得分:1)

  1. 如何将JSON数据存储在变量内或以某种方式本地存储?

您可以将其置于状态值,并使用本地存储进行存储。

状态值传递

 this.state ={ jsondata:{}}
...
            .then((responseJson) => {
                this.setState({
                    isLoading: false,
                    dataSource: responseJson.shosfc.weekday[7],
                    jsondata = responseJson
                });
                console.log(this.state.jsondata);
              }

本地存储数据

import {AsyncStorage} from 'react-native';
...

            .then((responseJson) => {
                this.setState({
                    isLoading: false,
                    dataSource: responseJson.shosfc.weekday[7],
                });
           AsyncStorage.setItem('jsondata', JSON,stringify(responseJson));
              }
  1. 如果要对JSON数据运行JavaScript函数,该在哪里做?在单独的组件的render()函数内部?

我发现这个问题很难理解。但是我知道这个问题的答案是,您可以声明和使用JSON之外的函数。


thisfunc(){
 alert("function in Json")
}
...
            .then((responseJson) => {
                this.setState({
                    isLoading: false,
                    dataSource: responseJson.shosfc.weekday[7],
                });
               this.thisfunc.bind(this)
              }

答案 1 :(得分:1)

在状态下添加jsonResponse尝试这个。

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

export default class FetchExample extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isLoading: true,
      dataSource: [],
      apiResponseJson:null
    };
  }

  // make an API call in the beginning
  componentDidMount() {
    return fetch('https://api.myjson.com/bins/18o9sd')
      .then(response => response.json())
      .then(responseJson => {
        this.setState(
          {
            isLoading: false,
            dataSource: responseJson.shosfc.weekday[7],
            apiResponseJson : responseJson.shosfc
          },
        );
      })
      .catch(error => {
        console.error(error);
      });
  }

  render() {
    if (this.state.isLoading) {
      return (
        <View style={{ flex: 1, padding: 50 }}>
          <ActivityIndicator />
        </View>
      );
    }

    return (
      <View style={{ flex: 1, paddingTop: 50 }}>
        <FlatList
          data={this.state.dataSource}
          renderItem={({ item }) => <Text>{item.min}</Text>}
          // keyExtractor={({id}, index) => id}
        />
        {console.log(this.state.apiResponseJson)}
      </View>
    );
  }
}