最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Loading Json response to a dropdown in react native - Stack Overflow

programmeradmin9浏览0评论

I'm using a material dropdown in my application

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

I fetch JSON object like this and it works fine.

  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.

I'm using a material dropdown in my application

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

I fetch JSON object like this and it works fine.

  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.

Share Improve this question edited Mar 2, 2018 at 23:24 Uddhav P. Gautam 7,6263 gold badges51 silver badges67 bronze badges asked Feb 23, 2018 at 10:57 ajithes1ajithes1 4272 gold badges11 silver badges29 bronze badges 1
  • Where are you calling fetch from ? – Andres C. Viesca Commented Mar 3, 2018 at 10:30
Add a comment  | 

5 Answers 5

Reset to default 12 +25

Supposing that you're using react-native-material-dropdown.

Example:

Dropdown component should be rendered as follows:

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

Request code:

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

Doc:

  • React native state management

  • react-native-material-dropdown

You can achieve this by using react native "state". Create a state then assign it to Dropdown component's data property. Then set responseJson.message.Obj[i].names to the state by using "this.setState()" method.

  • Find out what is the shape of the data property needed (i.e. Array of Objects) for the <Dropdown /> component you are using
  • Make fetch calls inside componentDidMount
  • Treat the state of your component as if it were immutable (do not push directly to this.state. dropdownData)

Here is some sample code using 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
          />
          // ...
        );
      }
      // ...
    }

See: AJAX Requests in React

See: react-native-material-dropdown expected data type

Sample code

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
}

});

You could also take an approach like this:

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?

You now have a few options you could set the state. From your example, you would set the state the state of your list to the data returned from the fetch call once it has been rendered. A quick thing to keep in mind is that react doesn't support asynchronous loading currently. Therefore the data must be rendered as empty, or with some sample data and then updated once the call has been made to whatever you wish to update! Hope this helps a little :) https://reactjs.org/docs/faq-ajax.html

发布评论

评论列表(0)

  1. 暂无评论