【问题标题】:How to get JSON dynamic value in Picker React-native如何在 Picker React-native 中获取 JSON 动态值
【发布时间】:2019-02-20 10:38:14
【问题描述】:

我正在尝试在 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"
}

谢谢

【问题讨论】:

    标签: javascript ajax reactjs react-native


    【解决方案1】:

    您的代码中存在一些问题

    1. 您的componentDidMount 中不需要返回声明
    2. 您没有正确访问 responseJson 中的值,没有名为 messages 的键
    3. 当您可以使用来自responseJson 的数组时,您正在使用for-loop
    4. 在您的选择器中,您将覆盖 PickerValueHolder,它会在您每次移动选择器时保存所有值。

    我对您的代码进行了一些更改,这是一个工作示例,您可以在此小吃 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,
      }
    });
    

    【讨论】:

    • 谢谢 Andrew,让我试试看,但是你在这里使用过 expo 吗?
    • Expo 是 react-native,它是一个很好的测试和原型设计工具。如果它在 Expo 中运行,它将在完整的 react-native 应用程序中运行。
    • 谢谢安德鲁,谢谢你教给我这一切..我很快就会学会这一切..谢谢:)
    • 嗨 Andrew,你能帮我再问一个问题吗,在那之后我不会打扰你..stackoverflow.com/questions/54801602/…
    【解决方案2】:
    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,
      }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-26
      • 1970-01-01
      • 1970-01-01
      • 2019-03-01
      • 2016-12-29
      • 1970-01-01
      相关资源
      最近更新 更多