简体   繁体   中英

How to render return fetch results in react-native helloWorldApp?

I'm an Android developer, but am new to JavaScript or react-native. I was following Facebook's react-native tutorial and I was able to copy-paste its sample code into my index.android.js and click 'RR' key to see the resulting UI in my simulator, until this network section. The code sample does not show how fetch is hooked up with render(), therefore is just an excerpt and no longer compilable. I tried to put it within render(){return like below code, but it throws error

myFetch.render(): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.

class myFetch extends Component{


render(){
    return (

    fetch('https://facebook.github.io/react-native/movies.json')
    .then((response) => response.json())
    .then((responseJson) => {
        return responseJson.movies;
    })
    .catch((error) => {
        console.error(error);
    })

    );
};
}

AppRegistry.registerComponent('HelloWorldApp', () => myFetch);

How to fix it in the simplest way, and what are the pointers to read, please?

class myFetch extends Component{
    constructor(props){
        super(props);
        this.state = {movies: 'init'};
    }

componentDidMount() {
     fetch('https://facebook.github.io/react-native/movies.json')
        .then((response) => response.json())
        .then((responseJson) => {this.setState({movies: responseJson.title});})
        .catch((error) => {
            console.error(error);
        })
}

render(){
    return (
      <Text>{this.state.movies}</Text>
    );
}

}

AppRegistry.registerComponent('HelloWorldApp', () => myFetch);

The render() method must return a React element (or null) like <View></View> .

And the network request should implement in componentDidMount() or other Lifecycle method .

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