2016-09-18 46 views
0

我是一名Android開發人員,但剛接觸JavaScript或反應原生。我正在關注Facebook的反應原生tutorial,我能夠將其示例代碼複製粘貼到我的index.android.js中,並單擊'R-R'鍵查看模擬器中生成的UI,直到此網絡部分。該代碼示例沒有顯示如何將提取與render()聯繫起來,因此只是一個摘錄,不再可編譯。我試圖把它放在render(){return像下面的代碼,但它拋出錯誤如何在react-native helloWorldApp中呈現返回提取結果?

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

如何解決此問題的最簡單的方式,什麼是讀指針,好嗎?

回答

1

渲染()方法必須返回一個React element (or null)<View></View>

而網絡請求應在componentDidMount()或其他Lifecycle method執行。

3
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); 
+0

請向您的代碼提供一些信息 – dv3