如何将从获取的返回数据中获得的数据数组放到Dropdown组件中?

时间:2018-09-13 09:43:06

标签: json react-native fetch

我正在尝试制作一个简单的下拉列表,该列表从获取返回中获取数据。 如果我使用控制台查看退货,则显示如下:

[
  {
    "ID": "BOGOR~10"
    "Location": "BOGOR"
  },

  {
    "ID": "JADETABEK~16"
    "Location": "JADETABEK"
  }
]

如果我想将BOGOR和JADETABEK放置在Dropdown中,该怎么办?这是我的测试课

import React , { Component } from 'react';
import { View , StyleSheet , Text , Dimensions } from 'react-native';
import { Dropdown } from 'react-native-material-dropdown';

const ScreenWidth = Dimensions.get('window').width;
const Screenheight = Dimensions.get('window').height;

export default class testing extends Component {

    constructor(props) {
        super(props)
        this.state = {
            data: []
        }
    }

    componentDidMount() {
        fetch(url , {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({"lokasi":
                {

                }
            })
        })
        .then(response => response.json())
        .then(res => {
            this.setState({
                data: res.PilihLokasiResult.Lokasi    
            })
            alert(res.PilihLokasiResult.Lokasi)
        })
    }

    render() {
        return(
            <View style={styles.container}>
                <View>
                    <Text>{this.state.location}</Text>
                    <Dropdown label="select location" style={{width: 400 }}/>
                </View>
            </View>
        )
    }
}

1 个答案:

答案 0 :(得分:0)

您需要格式化数据,因为react-native-material-dropdown接受{value: 'Sample'}形式的数据

this.state = {
  data: [],
  dropDownData: []
}

const formatData = (data) => {
  return data.map(dataObj => {
    return {value: dataObj.Location} // return based on location
  })
}

.then(res => {
   const dropDownData = formatData(res.PilihLokasiResult.Lokasi)
   this.setState({
     data: res.PilihLokasiResult.Lokasi,
     dropDownData    
   })
})

<Dropdown label="select location" data={this.state.dropDownData} style={{width: 400 }}/>