如何在Picker React-native中获取JSON动态值 [英] How to get JSON dynamic value in Picker React-native

查看:107
本文介绍了如何在Picker React-native中获取JSON动态值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里试图在Picker中获取值,我正在以JSON格式获取值,并试图在Picker中显示该值,例如DropDown。
请帮助。下面的代码试图像打和审判,但不能正常工作。
以下是我的代码和JSON值。
我需要安装和依赖吗?

Here am trying to get value in Picker , I am getting value in JSON format and trying to show that value in Picker like DropDown . Please help. Below code am trying like hit and trial but not working . Below is my code and JSON value also . Do I need to install and dependencies ?

 import React, { Component } from 'react';

    import { AppRegistry, StyleSheet, View, Platform, Picker, ActivityIndicator, Button, Alert} from 'react-native';

    export default class AddInventory extends Component {

     componentDidMount() {

          return  fetch('http://1/Dsenze/userapi/inventory/viewinventorytype', {  
            method: 'POST',
            headers: {
              'Accept': 'application/json',
              'Content-Type': 'application/json',
            },
            body: JSON.stringify({
              "username" :"admin",
              "password" :"admin"
            })
          }).then((response) => response.json())
          .then((responseJson) => {
            var count = Object.keys(responseJson.message.Obj).length;
            let PickerValueHolder = [];
            for(var i=0;i<count;i++){
              console.log(responseJson.message.Obj[i].name) // I need to add 
              PickerValueHolder.push({ value: responseJson.message.Obj[i].name }); // Create your array of data
            }
            this.setState({ PickerValueHolder }); // Set the new state
          })
          .catch((error) => {
            console.error(error);
          });
        }

        GetPickerSelectedItemValue=()=>{

          Alert.alert(this.state.PickerValueHolder);
        }

     render() {

       return (

        <View style={styles.MainContainer}>

              <Picker
                selectedValue={this.state.PickerValueHolder}
                onValueChange={(itemValue, itemIndex) => this.setState({PickerValueHolder: itemValue})} >
                { this.state.dataSource.map((item, key)=>(
                <Picker.Item label={item.name} value={item.name} key={key} />)
                )}

              </Picker>

              <Button title="Click Here To Get Picker Selected Item Value" onPress={ this.GetPickerSelectedItemValue } />

        </View>

       );
     }
    }

    const styles = StyleSheet.create({

    MainContainer :{

    justifyContent: 'center',
    flex:1,
    margin: 10
    }

    });

//以下是JSON响应

// below is JSON response

{
  "inventoryTypeData": [{
    "id": 1,
    "name": "scanning equipment"
  }, {
    "id": 2,
    "name": "ecg machine"
  }, {
    "id": 3,
    "name": "ct-scan machine"
  }, {
    "id": 7,
    "name": "x-ray machine"
  }],
  "success": "true"
}

谢谢

推荐答案

您的代码中遇到了一些问题

You've got a few issues in your code


  1. 您不需要退货 componentDidMount
  2. 中的语句
  3. 您没有正确访问 responseJson ,没有称为消息的键

  4. 您正在使用 for循环时,只需使用 responseJson

  5. 在选择器中,您正在覆盖 PickerValueHolder ,其中包含所有每次值您可以移动选择器。

  1. You don't need a return statement in your componentDidMount
  2. You're not accessing the values correctly in your responseJson, there is no key called messages
  3. You are using a for-loop when you could just use the array from the responseJson.
  4. In your picker you are overwriting the PickerValueHolder which holds all the values each time you move the picker.

我对您的代码进行了一些更改,这是一个有效的示例,您可以在此处查看此小吃 https://snack.expo.io/@andypandy/picker-example

I have made some changes to your code, and this is a working example, which you can see here at this snack https://snack.expo.io/@andypandy/picker-example

import * as React from 'react';
import { Text, View, StyleSheet, Alert, Picker } from 'react-native';
import { Constants } from 'expo';

export default class App extends React.Component {

  // add a selectValue to your state to stop the overwriting
  state = {
    PickerValueHolder: [],
    selectedValue: ''
  }

  componentDidMount() {
    // remove the return 
   fetch('http://1/Dsenze/userapi/inventory/viewinventorytype', {  
        method: 'POST',
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          "username" :"admin",
          "password" :"admin"
        })
      }).then((response) => response.json())
      .then((responseJson) => {
        // use the inventoryTypeData as it is already an array
        let PickerValueHolder = responseJson.inventoryTypeData;
        this.setState({ PickerValueHolder }); // Set the new state
      })
      .catch((error) => {
        console.error(error);
      });
    }

  GetPickerSelectedItemValue=()=>{
    Alert.alert(this.state.PickerValueHolder);
  }

  render() {


    return (
      <View style={styles.container}>
        {<Picker
                selectedValue={this.state.selectedValue}
                onValueChange={(itemValue, itemIndex) => this.setState({selectedValue: itemValue})} >
                { this.state.PickerValueHolder.map((item, key)=>
                  <Picker.Item label={item.name} value={item.name} key={key} />
                )}
              </Picker>}
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
    padding: 8,
  }
});

这篇关于如何在Picker React-native中获取JSON动态值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆