加载 Json 响应本机下拉菜单

Loading Json response to a dropdown in react native

我在我的应用程序中使用 material 下拉列表

<Dropdown 
  baseColor='white'
  itemColor='white'
  label='Select Cluster'
/>

我像这样获取 JSON 对象,它工作正常。

  fetch('url', {  
    method: 'POST',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      username : "admin"
    })
  }).then((response) => response.json())
  .then((responseJson) => {
    var count = Object.keys(responseJson.message.Obj).length;
    for(var i=0;i<count;i++){
      console.log(responseJson.message.Obj[i].name) // I need to add 
      //these names to dropdown
    }
  })
  .catch((error) => {
    console.error(error);
  });

Now I need to add the responseJson.message.Obj[i].name values to my dropdown list.

您可以使用 React Native "state" 来实现这一点。创建一个状态,然后将其分配给 Dropdown 组件的数据 属性。然后使用"this.setState()"方法将responseJson.message.Obj[i].names设置为state.

假设您正在使用 react-native-material-dropdown

示例:

Dropdown 组件应呈现如下:

<Dropdown
  baseColor='white'
  itemColor='white'
  label='Select Cluster'
  data={this.state.drop_down_data} // initialise it to []
/>

请求代码:

fetch('url', {
  ...
}).then((response) => response.json())
.then((responseJson) => {
  var count = Object.keys(responseJson.message.Obj).length;
  let drop_down_data = [];
  for(var i=0;i<count;i++){
    console.log(responseJson.message.Obj[i].name) // I need to add 
    drop_down_data.push({ value: responseJson.message.Obj[i].name }); // Create your array of data
  }
  this.setState({ drop_down_data }); // Set the new state
})
.catch((error) => {
  console.error(error);
});

文档:

  • 找出您正在使用的 <Dropdown /> 组件 data 属性 所需的形状(即对象数组)
  • 在内部进行获取调用 componentDidMount
  • 将组件的 state 视为不可变的(不要 push 直接到 this.state. dropdownData

下面是一些使用 react-native-material-dropdown:

的示例代码
    class Example extends React.Component {
       // Use constructor to assign initial state
       constructor(props) {
         this.state = {
           dropdownData: []
         };
       }

      componentDidMount() {
        fetch('url', {  
          method: 'POST',
          headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            username : "admin"
          })
        })
        .then((response) => response.json())
        .then((responseJson) => {
          var count = Object.keys(responseJson.message.Obj).length;
          // We need to treat this.state as if it were immutable.
          // So first create the data array (tempDataArray) 
          var tempDataArray = [];
          for(var i=0;i<count;i++){
            // Note: react-native-material-dropdown takes an Array of Objects
            tempDataArray.push({
              value: responseJson.message.Obj[i].name
            });
          }
          // Now we modify our dropdownData array from state
          this.setState({
            dropdownData: tempDataArray
          });
        })
        .catch((error) => {
          console.error(error);
        });
      }

      // ...
      render() {
        return (
          // ...
          <Dropdown 
            baseColor='white'
            itemColor='white'
            label='Select Cluster'
            data={this.state.dropdownData} // Use dropdownData for the data prop
          />
          // ...
        );
      }
      // ...
    }

参见:AJAX Requests in React

参见:react-native-material-dropdown expected data type

您也可以采用这样的方法:

var Somedata = {
            "data" : [
                {
                "baseColor": "white",
                    "moreData":[
                        {
                            "id" : 118,
                        }
                    ]
                },
                {
                "baseColor": "grey",
                    "moreData": [
                        {
                            "id": 1231231,
                        }
                    ]
                }
            ]
        }
const renderData = someData.data.map((data) => {
        return data.moreData.map(brand => {
            strColor = data.baseColor;
            console.log("Individual Data :" + strColor)
                return `${data.baseColor}, ${moreData.id}`
                //setState here?
        }).join("\n")
    }).join("\n")
//setState here?

您现在有几个选项可以设置状态。在您的示例中,您可以将状态列表的状态设置为呈现后从提取调用返回的数据。需要牢记的一点是,React 目前不支持异步加载。因此,数据必须呈现为空,或带有一些示例数据,然后在调用了您希望更新的任何内容后进行更新!希望这有所帮助 :) https://reactjs.org/docs/faq-ajax.html

示例代码

import React, { Component } from 'react';

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

export default class AddInventory extends Component {

 constructor(props)
 {

   super(props);

   this.state = { 

   isLoading: true,

   PickerValueHolder : ''

  }
 }

 componentDidMount() {

      return fetch('https://reactnativecode.000webhostapp.com/FruitsList.php')
        .then((response) => response.json())
        .then((responseJson) => {
          this.setState({
            isLoading: false,
            dataSource: responseJson
          }, function() {
            // In this block you can do something with new state.
          });
        })
        .catch((error) => {
          console.error(error);
        });
    }

    GetPickerSelectedItemValue=()=>{

      Alert.alert(this.state.PickerValueHolder);

    }

 render() {

   if (this.state.isLoading) {
     return (
       <View style={{flex: 1, paddingTop: 20}}>
         <ActivityIndicator />
       </View>
     );
   }

   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.fruit_name} value={item.fruit_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
}

});