【问题标题】:How can i put the data array gained from the fetch return to the Dropdown component?如何将获取返回的数据数组放入 Dropdown 组件?
【发布时间】:2018-09-13 09:43:05
【问题描述】:

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

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

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

如果我想获取 BOGOR 和 JADETABEK 位置并将它们放入下拉列表中,我该怎么做?这是我的测试课

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>
        )
    }
}

【问题讨论】:

    标签: json react-native fetch


    【解决方案1】:

    由于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 }}/>
    

    【讨论】:

    • 我应该把 const formatData 放在哪里?它在构造函数下吗?对不起,我是初学者..
    • 在你的组件之外,因为它只是一个普通的格式化函数
    • 我试图将它放在导出默认类之外,它会抛出黄屏,提示可能未处理的承诺拒绝 (id:0): TypeError: data.map is not a function
    • 是的,课外的任何地方
    • 尝试检查你在第一个sn-p中添加的结果应该传递给函数,我不知道这是否正确
    猜你喜欢
    • 1970-01-01
    • 2013-12-24
    • 1970-01-01
    • 2016-03-19
    • 1970-01-01
    • 2019-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多