我使用以下代码从已发布的API源获取和呈现数据,但在成功获取控制台上的数据后无法设置状态。以下是我的代码;
// ########## Import Dependencies Here ##########
import React, { Component } from 'react';
import { View, Text, ListView, TouchableOpacity, ActivityIndicator, StyleSheet, StatusBar, Dimensions, RefreshControl, Platform } from 'react-native';
import { Container, Card, CardItem, Content, Left, Right, Icon } from 'native-base';
import FitImage from 'react-native-fit-image';
import TimeAgo from 'react-native-timeago';
import HTML from 'react-native-render-html';
// ########## Import Screens Here ##########
import ReadMore from './ReadMore';
// ########## Import Components Here ##########
import { contentText, contentURL } from '../helpers/helpers';
const {height, width} = Dimensions.get('window');
export default class Home extends Component {
constructor(props) {
super(props);
this.state = {
rowData: [],
isLoading: true,
}
}
componentWillMount() {
return fetch('https://vinth.azurewebsites.net/wp-json/wp/v2/posts')
.then((response) => response.json())
.then((responseJson) => {
console.log('will mount')
console.log(responseJson);
console.log('state',this.state);
let ds = new ListView.DataSource({
rowHasChanged: (r1, r2) => r1 !== r2
});
this.setState({
isLoading: false,
dataSource: ds.cloneWithRows(responseJson),
}, function () {
// do something with new state
});
console.log('state',this.state);
})
.catch((error) => {
console.error(error);
});
}
render() {
return (
<Container>
<View>
<StatusBar
barStyle="light-content"
/>
</View>
<ListView
dataSource={this.dataSource}
renderRow={
(rowData) =>
<View>
<TouchableOpacity onPress={() => this.props.navigation.navigate('ReadMore', { rowData })}>
<Card>
<CardItem header>
<Text style={styles.titleHeading}>{rowData.title.rendered}</Text>
</CardItem>
<CardItem cardBody>
<Content style={styles.cardContainer}>
<FitImage
source={{ uri: contentURL(rowData.better_featured_image.source_url) }}
style={{ width: width, height: 200 }}
/>
<HTML tagsStyles={bodyText} html={contentText(rowData.excerpt.rendered)} />
</Content>
</CardItem>
<CardItem style={styles.borderLine}>
<Left>
</Left>
<Right>
</Right>
</CardItem>
</Card>
</TouchableOpacity>
</View>
}
/>
</Container>
);
}
}
奇怪的是,componentWillMount代码在我以前在React Native(0.50.0)中完成的一个应用程序中运行。目前我正在使用React Native 0.53.0版本。
答案 0 :(得分:0)
因此,在此方法中同步调用setState()不会触发额外的渲染
您不能使用componentDidMount()
吗?
(我知道它是RN而不是React,但在我看来最近发生了一些重大变化)