简体   繁体   中英

How to fetch php created json to react native

I've created a table in mysql, for some news data. it comprises of title, body, and link to the image. The file, is saved on example.com/api/news.php, and by following the link will result in an array, something like this:

[{"id":"1","title":"News Title 1","body":"Body 1","date":"2020-12-01","image":"Image 1","link":"Link 1"},{"id":"2","title":"Title 2","body":"Body 2","date":"2020-12-17","image":"Image 2","link":"https:\/\/google.com"},{"id":"3","title":"Title 3","body":"Body 3","date":"2020-12-24","image":"Image 3","link":""}]

In react native, I tried to fetch by following examples:

constructor(props){
    super(props);
    this.state = {
      isLoading: true,
      data: null
    }
  }

  componentDidMount(){
    return fetch('https://example.com/api/news.php')
    .then((response) => response.json())
    .then((json) => {
      this.setState({
        isLoading: false,
        data: json.id,
      })
    })
    .catch((error) => {
      console.error(error);
    });
  }

  render(){
    if(this.state.isLoading){
      return(
        <View style={styles.container}>
          <ActivityIndicator/>
        </View>
      )
    }else{
      return(
        <View style={styles.container}>
          <Text>Content Loaded!</Text>
        </View>
    )
    }
    
  } 

However, the activity indicator keeps on running. While, when I tried using the original API link from the example which is https://reactnative.dev/movies.json , its working fine. May I know what is the problem that is blocking the json to be read. Thanks for your guidance.

Remove return from code and maybe you are getting an error in response, try reset isLoading state in error like

componentDidMount(){
   fetch('https://example.com/api/news.php')
    .then((response) => response.json())
    .then((json) => {
      this.setState({
        isLoading: false,
        data: json.id,
      })
    })
    .catch((error) => {
      console.error(error);
      this.setState({ // add this code
        isLoading: false
      })
    });
}

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