简体   繁体   中英

problem in get fetch data in react-native

I am a react-native beginner. I get following data from the server:

[{"id":"1","tmb":"23\/5\/96","name":"ehsan","family":"kharaman"}]

My goal is to display this data in the render method.

My code is:

import React, {Component} from 'react';
import {View, Text} from 'react-native';

class App extends Component {
  state = {
    data: '',
  };
  componentDidMount = () => {
    fetch('http://192.168.1.34/karbar/select.php', {
      method: 'GET',
    })
      .then(response => response.json())
      .then(responseJson => {
        console.log(responseJson);
        this.setState({
          data: responseJson,
        });
      })
      .catch(error => {
        console.error(error);
      });
  };
  render() {
    return (
      <View>
        <Text>{this.state.data.name}</Text>
      </View>
    );
  }
}
export default App;

my friend,

Note that your data is an array, not an object,

To see the name you should put something like that

<Text>{this.state.data[0].name}</Text>

To have access to the first element on the result array.

please. Also note that if your answer is an array, the default value for the data in your state must be an empty array and not a simple string.

this link can help you to show properly the answer in your case

https://reactjs.org/docs/lists-and-keys.html

also you should check conditional rendering https://reactjs.org/docs/conditional-rendering.html

Till you make the fetch call to get data and you get data, your state will have data as an empty string, because in constructor you have initialized it so. A good practice would be to initialize it to an empty array because data will be an array after the fetch

state = {
    data: [],
};

And in render, check if data exists before picking out name from data. Also data is an array, so you have to get the first element before picking out name ( data[0].name )

render() {
    if (this.state.data.length > 0) {
        return (
            <View>
              <Text>{this.state.data[0].name}</Text>
            </View>
          );
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM