【问题标题】:How to render return fetch results in react-native helloWorldApp?如何在 react-native helloWorldApp 中呈现返回获取结果?
【发布时间】:2016-09-18 06:12:07
【问题描述】:

我是一名 Android 开发人员,但不熟悉 JavaScript 或 react-native。我正在关注 Facebook 的 react-native tutorial,我能够将其示例代码复制粘贴到我的 index.android.js 中,然后单击“R-R”键在我的模拟器中查看生成的 UI,直到这个网络部分。代码示例没有显示 fetch 如何与 render() 挂钩,因此只是摘录,不再可编译。我试图把它放在 render(){return 如下代码中,但它抛出错误

myFetch.render():必须返回一个有效的 React 元素(或 null)。您可能返回了未定义、数组或其他一些无效对象。

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

如何以最简单的方式修复它,请阅读哪些指针?

【问题讨论】:

    标签: react-native fetch


    【解决方案1】:
    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);
    

    【讨论】:

      【解决方案2】:

      render() 方法必须返回一个React element (or null),如&lt;View&gt;&lt;/View&gt;

      并且网络请求应该在componentDidMount()或其他Lifecycle method中实现。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-06-18
        • 1970-01-01
        • 2021-12-13
        • 2019-06-17
        • 2022-01-23
        • 1970-01-01
        相关资源
        最近更新 更多