如何在Picker React-native中获取JSON动态值

时间:2019-02-20 10:38:15

标签: javascript ajax reactjs react-native

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

 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响应

{
  "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"
}

谢谢

2 个答案:

答案 0 :(得分:1)

您的代码中有几个问题

  1. 您不需要在componentDidMount中使用return语句
  2. 您没有正确访问responseJson中的值,没有称为消息的键
  3. 当您只使用for-loop中的数组时,就在使用responseJson
  4. 在选择器中,您覆盖了PickerValueHolder,每次移动选择器时,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, } }); 都包含所有值。

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

中看到
sys.argv

答案 1 :(得分:1)

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

export default class AddInventory extends React.Component {

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

  componentDidMount() {
    // remove the return 
   fetch('http:///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',
    backgroundColor: '#ecf0f1',
    padding: 8,
  }
});