2017-06-12 60 views
0

陣營天然由實教程返回錯誤取JSON陣營天然由實教程返回錯誤取JSON

具有空的錯誤是不是一個對象(評價「this.state.datasource」)

我該怎麼辦我的代碼

class ModuleRecView extends Component { 
    componentWillMount() { 

     return fetch('https://facebook.github.io/react-native/movies.json') 
     .then((response) => response.json()) 
     .then((responseJson) => { 
      let ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}); 
      this.setState({ 
      isLoading: false, 
      dataSource: ds.cloneWithRows(responseJson.movies), 
      }, function() { 
      // do something with new state 
      }); 
     }) 
     .catch((error) => { 
      console.error(error); 
     }); 

    } 
    render() { 

     return (
     <View style={{flex: 1, paddingTop: 20}}> 
      <ListView 
      dataSource={this.state.dataSource} 
      renderRow={(rowData) => <Text>{rowData.title}, {rowData.releaseYear}</Text>} 
      /> 
     </View> 
    ); 
    } 
} 

export default ModuleRecView; 

回答

0

右上面componentWillMount做:

constructor() { 
    super(); 
    const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}); 
    this.state = { 
    dataSource: ds.cloneWithRows([]), 
    }; 
} 
+0

插入後的數據這段代碼是錯**找不到變量:DS ** 我怎麼能與此錯誤,請 –

+0

'狀態= { dataSource:ds.cloneWithRows([]), } componentWillMount(){ return fetch('https://facebook.github.io/react-native/movies.json') .then((response)=> response.json()) .then((responseJson)=> {} {} {}};}}; this.setState({isLoading:false, dataSource:ds.cloneWithRows(responseJson.movi​​es), },function(){ //用新狀態做某事 }); })' –

+0

噢是真的,病更新我的答案使用構造函數來定義DS。 –

0

我通常不喜歡這樣:

import React, { Component } from 'react' 
import { ListView, View, Text } from 'react-native' 

class ModuleRecView extends Component { 
    state = { 
    datasource: new ListView.DataSource({rowHasChanged: (r1, r2) => r2 !== r2}), 
    isLoading: true 
    } 

    componentWillMount() { 
    fetch('https://facebook.github.io/react-native/movies.json') 
    .then((response) => response.json()) 
    .then((responseJson) => { 
     this.setState({ 
     isLoading: false, 
     dataSource: this.state.datasource.cloneWithRows(responseJson.movies), 
     },() => { 
     // do something with new state 
     }); 
    }) 
    .catch((error) => { 
     console.error(error); 
    }); 
    } 

    render() { 
    return (
     <View style={{flex: 1, paddingTop: 20}}> 
     <ListView 
      dataSource={this.state.datasource} 
      renderRow={(rowData) => <Text>{rowData.title}, {rowData.releaseYear}</Text>} 
     /> 
     </View> 
    ); 
    } 
} 

export default ModuleRecView; 

請注意,RN現在有一個新的組件叫做< FlatList />這是一樣的<ListView/>成分,但遠遠好。