React-Native获取示例未呈现

时间:2018-06-11 11:13:14

标签: react-native

我是React和React-Native的新手,并且遵循official website上的React原生文档。我正在使用fetch调用我的API端点。返回的JSON正在Developer's工具的控制台上显示,但它不在Application中呈现。我可以看到所有控制台日志,但不能看到应用程序。

此外,如果我将我的FetchExample组件作为默认类,那么UI就可以正常渲染。问题出在哪儿?请帮忙。

class FetchExample extends Component {
  constructor(props){
    super(props);
    this.state ={ isLoading:true}
  }
  componentDidMount(){
      console.log(" mounting")
      return fetch('https://evening-escarpment-86286.herokuapp.com/todo')
      .then((response) => response.json())
      .then((responseJson) => {
        this.setState({
          isLoading: false,
          dataSource: responseJson,
        }, function(){

        });

      })
      .catch((error) =>{
        console.error(error);
      });
  }
  render(){
    if(this.state.isLoading){
      return(
        <View style={{flex: 1, padding: 20}}>
          <ActivityIndicator/>
        </View>
      )
    }
    console.log(this.state.dataSource);
    console.log("hi")
    return(
      <View style={{flex: 1, paddingTop:20}}>

        <FlatList
          data={this.state.dataSource}
          renderItem={({item}) => <Text>{item.id}, {item.name}, {item.message}, {item.time}</Text>}
          keyExtractor={(item, index) => index.toString()}
        />
      </View>
    );
  }
}

export default class LotsOfGreetings extends Component{
  render(){
    return (
      <View style={{alignItems: 'center',  marginTop: 30}}>
        <FetchExample />
      </View>
    );
  }
}
// skip this line if using Create React Native App
AppRegistry.registerComponent('AwesomeProject', () => LotsOfGreetings);

2 个答案:

答案 0 :(得分:0)

您可以尝试初始化一个dataSource以查看它是否有效吗?

constructor(props){
    super(props);
    this.state = { isLoading:true, datasource: []}
}

答案 1 :(得分:0)

嗯,这个问题是通过将API调用(fetch)放在构造函数本身而不是在componentDidMount方法中解决的。虽然我认为这不是一个好方法,但React-Native documentation说我们应该在componentDidMount方法中进行API调用。

相关问题