下面是主视图屏幕,它获取数据,然后将其获取到渲染组件。由于某种原因,内容没有被附加,而是由新的内容替换。
export default class Questions extends React.Component {
constructor(props)
{
super(props);
this.state = {
data:[],
options_array: [],
last_id: 0,
username: '',
image_url:''
};
}
loadInitialState = async () => {
this.state.username = await AsyncStorage.getItem('user'); //This should be tranfered from the login
this.state.image_url = await AsyncStorage.getItem('image_url');
this.getData();
};
getData()
{
return fetch('url.com/endpoint', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
username: this.state.username,
last_id: this.state.last_id,
options_array: this.state.options_array
})
})
.then((response) => {
console.log(response);
return response.json()
})
.then((res) => {
this.setState({data: res.questions});
this.setState({last_id:res.last_id});
})
.catch((error) => {
console.error(error);
});
}
componentDidMount()
{
this.loadInitialState().done();
}
render()
{
return (
<Content>
<TouchableOpacity onPress={()=>this.props.navigation.navigate("PostQuestion")}>
<Card transparent>
<CardItem>
<Left>
<Thumbnail small source={{uri: this.state.image_url}} />
<Body>
<Text style={styles.poster_username}>{this.state.username}</Text>
<Text style={styles.moto1}>Help others help you</Text>
</Body>
</Left>
</CardItem>
</Card>
</TouchableOpacity>
<QuestionsData data={this.state.data} navigation = {this.props.navigation}/>
<Button title='Load' onPress={()=>this.loadInitialState().done()}/>
</Content>
);
}
}
以下是渲染的地方
export default class QuestionsData扩展了React.Component { 构造函数(道具) { 超级(道具); this.state = { 导航:null } }
componentDidMount()
{
this.state.navigation = this.props.navigation;
console.log(this.props)
}
questionList(props)
{
return props.data.map(function (questionData, index)
{
return renderQuestionContent(questionData, props)
}
);
}
render()
{
return this.questionList(this.props)
}
}
答案 0 :(得分:0)
我设法解决了问题,我用this.setState({data: res.questions});
替换this.setState({data: [ ...this.state.data, ...res.questions ]});
然后它工作得很好