繁体   English   中英

如何在react-native helloWorldApp中呈现返回获取结果?

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

我是一名Android开发人员,但不熟悉JavaScript或react-native。 我正在关注Facebook的本机教程,并且能够将其示例代码复制粘贴到我的index.android.js中,然后单击“ RR”键以在模拟器中查看生成的UI,直到该网络部分。 代码示例未显示如何将获取与render()挂钩,因此仅是摘录,不再可编译。 我试图将其放在render(){返回,如下面的代码,但它引发错误

myFetch.render():必须返回有效的React元素(或null)。 您可能返回了undefined,数组或其他无效对象。

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

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

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

render()方法必须返回类似<View></View>React element (or null)

网络请求应在componentDidMount()或其他Lifecycle方法中实现

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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