React-Native:显示JSON数据

时间:2019-09-07 06:08:48

标签: reactjs react-native

   
function getData(access_token) {
  fetch('https://api.fitbit.com/1/user/-/activities/steps/date/today/1m.json', {
    method: 'GET',
    headers: {
      Authorization: `Bearer ${access_token}`,
    },
    // body: `root=auto&path=${Math.random()}`
  })
    .then(res => res.json())
    .then(res => {
      console.log(`res: ${JSON.stringify(res)}`);
    })
    .catch(err => {
      console.error('Error: ', err);
    });
}
export default class App extends Component {
  
  connectFitbit = () => {
    OAuth(client_id, getData);
  };

  render() {
    
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>Welcome to Fitbit Integration</Text>
        <Button title="connect fitbit" onPress={() => this.connectFitbit()} />
      </View>
    );
  }
}

我正在尝试在本机应用程序中获取适合的步骤JSON数据, 现在我正在控制台中获取输出,现在我想解析应用程序中的步骤数据,请帮帮我

1 个答案:

答案 0 :(得分:0)

如果您想将数据显示在清单中...

首先,您需要创建一个数组来保存响应数据。

constructor(props) {
    super(props);
    this.state = {
     ...
      result: [],
     ...
    };
  }

function getData(access_token) {
  fetch('https://api.fitbit.com/1/user/-/activities/steps/date/today/1m.json', {
    method: 'GET',
    headers: {
      Authorization: `Bearer ${access_token}`,
    },

  })
    .then(res => res.json())
    .then(res => {
      console.log(`res: ${JSON.stringify(res)}`);
      // if your response have anu json array
        this.setState({
            result:res.data,
          });
    })
    .catch(err => {
      console.error('Error: ', err);
    });
}

在平面列表中,只需设置此数组,

<FlatList
      data={this.state.result}
        renderItem={item => your render view}
        keyExtractor={(item, index) => your key item}/>