【发布时间】:2016-08-19 21:33:51
【问题描述】:
我正在尝试在 componentWillReceiveProps 执行时刷新列表视图。获取后似乎 dataSource 已更新(我将 console.log(this.state.dataSource) 放入 render() 并根据端点的当前状态更改。)
但是,ListView 保持不变。我想知道为什么并对 dataSource 持怀疑态度。所以我最终制作了字符串对象以在渲染()中打印出数据源。 var str = JSON.stringify(this.state.dataSource._dataBlob.s1);
还有<View><Text>{str}</Text>
当 componentWillReceiveProps() 执行时,上述部分发生了变化。但是,列表视图保持不变。我不知道为什么会这样。
这是我的代码的 sn-p。
componentWillReceiveProps(){
var query = ApiUrl.urlForWeekInfo(this.state.email);
console.log(query);
this._executeQuery(query,3);
}
constructor(props) {
super(props);
var dataSource = new ListView.DataSource(
{rowHasChanged: (r1, r2) => r1.guid !== r2.guid});
this.state = {
isLoading: false,
...
first_name: this.props.first_name,
email: this.props.email,
dataSource: dataSource.cloneWithRows(this.props.listings)
};
}
..
_executeQuery(query,i) {
this.setState({ isLoading: true });
fetch(query)
.then(response => response.json())
.then(json => this._handleResponse(json.response,i))
.catch(error =>
this.setState({
isLoading: false,
message: 'Something bad happened ' + error
}));
}
_handleResponse(response,i) {
this.setState({ isLoading: false , message: '' });
if (response.application_response_code.substr(0, 1) === '1') {
if(i==1){
this.props.navigator.push({
title: 'Apply',
component: Apply,
passProps: {listings: response.listings, times: response.timetable, week_num: this.state.week_num}
});
} else if (i==3){
var output = response.listings;
this.setState({
dataSource: this.state.dataSource.cloneWithRows(output)
});
console.log(response.listings);
this.forceUpdate();
}
} else {
}
}
render() {
console.log(this.state.dataSource._dataBlob.s1);
var str = JSON.stringify(this.state.dataSource._dataBlob.s1);
var listviewsource = this.state.dataSource;
return (
<View style={[this.border('red'), styles.container_top]}>
<View style={[this.border('black'), styles.container_top_buttons]} >
<ListView
dataSource={listviewsource}
renderRow={this.renderRow.bind(this)}/>
</View>
{spinner}
<View>
<Text>{str}</Text>
</View>
</View>
);
}}
请分享您可能有的任何想法或经验。
我最终找到了解决这个问题的方法:
var array = response.listings;
var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
//=> call another ds variable.
this.setState({
rawData: array,
dataSource: ds.cloneWithRows(response.listings)
});
【问题讨论】:
标签: listview react-native