最近在改動ListView時發現ListView數據不是在進入界面之後就加載出來,而是要點擊屏幕之後纔會加載數據,很怪異的bug。
首先函數是這麼寫的:在fetchInfo()裏去獲取服務器裏的個人信息,然後再設置到頁面。整理之後發現還是邏輯問題,以後得多注意思維清晰。
fetchInfo() {
if(!this.state.fetched) {
var body = {
userId: this.state.user_id,
} ;
var getSign = this.state.sign.toUpperCase() ;
var getParams = 'userId=' + this.state.user_id + '&token=' + this.state.token ;
var paramSign = md5(getParams) ;
SELFINFO_REQUEST = SELFINFO_URL + '?sign=' + paramSign.toUpperCase() + '&body=' + JSON.stringify(body) ;
var infoRequest = encodeURI(SELFINFO_REQUEST) ;
fetch(infoRequest)
.then((response) => response.json())
.then((response) => {
this.setInfo(response);
})
.then(() => {
this.setState({
fetched: true
})
)
}
}
setInfo(response) {
const status = response.status ;
const msg = response.msg ;
if(status == 0 ) {
var data = response.data ;
var groupName = data.groupName ;
var name = data.name ;
var mobile = data.mobile ;
this.setState({
group: groupName,
name: name ,
tel: mobile,
})
} else {
ToastAndroid.show('個人信息獲取失敗,請重新登錄!',ToastAndroid.SHORT) ;
...
}
}
_changePwd() {
const { navigator } = this.props ;
if(navigator) {
navigator.push({
name:' ChangePwd' ,
component: ChangePwd ,
})
}
}
_logOut() {
AsyncStorage.setItem('isLogin','false').then(() => {
AsyncStorage.setItem('user_id','null').then(() => {
AsyncStorage.setItem('token','null') ;
}) ;
}).then(() => {
const { navigator } =this.props ;
if(navigator) {
navigator.push({
name: 'App' ,
component: App ,
})
}
}).done() ;
}
render() {
if(!this.state.fetched) {
return (
<View style = {styles.loadContainer}>
<Text style = {styles.loadTxt} >加載中...</Text>
</View>
)
} else {
return (
<View style = {styles.container} >
...
</View>
);
}
}
問題出現了,每次都必須要點擊屏幕之後才能加載數據,後來一看邏輯,覺得自己被狗日了。。。。
原因是我在setInfo裏去設置個人信息,但是在fetchInfo裏已經設置了fetched爲true,這樣render就不會再執行下面的操作了。把
this.setState({
fetched: true
})
這句話設置到setInfo裏的setState函數裏就可以了。
PS:最近版本的RN,在開啓Chrome調試時也會出現點擊屏幕才加載的bug,不過也可能是官方故意這麼做的,畢竟以前是沒有這個bug的,而且一到Chrome調試,App就會特別卡,略醉。