React Native 组件生命周期方法未按正确顺序调用
React Native Component lifecycle methods not getting called in proper sequence
根据这些链接 React Native Component Lifecycle and Component Lifecycle,componentWillMount
方法应该在 render
方法之前被调用,但在我的项目中并非如此。我正在 componentWillMount
中执行 fetch
操作,但在执行操作时,render
方法在 componentWillMount
完成之前被调用。这是我的 class:
class UserHomeScreen extends Component {
state = { userID: '' };
componentWillMount(){
AsyncStorage.getItem('userId').then((value) => {
this.setState({ userID: value });
const API_ENDPOINT= 'https://myserverAPI';
const userID = value;
fetch(API_ENDPOINT,{ method: "GET",
headers:{
'Authorization': 'Bearer '+ userID
}
})
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
userInfo = new UserInfo();
userInfo.updateValues(responseJson);
AsyncStorage.setItem("userInfo",JSON.stringify(userInfo),null);
backInfo = AsyncStorage.getItem("userInfo").then(value);
})
});
}
render(){
return(
<Text>hello { this.state.userID }
</Text>
)
}
}
它们以正确的生命周期顺序被调用。您的问题出在 fetch
中,因为 Fetch API returns a Promise
不是同步的。如果你在承诺中设置状态,你可以通过强制 re-render 来解决这个问题,例如
this.setState({mode = 'loading'})
API.fetch().then(this.setState({mode = 'finished'})); // pseudo code
或强制等待 Promise
。我会选择选项一并在您的渲染方法中设置一个占位符,例如
render() {
return (
this.state.mode == "loading" ? <div>"Loading..." </div> :
<div>{do your stuff with the fetched response}</div>
}
根据这些链接 React Native Component Lifecycle and Component Lifecycle,componentWillMount
方法应该在 render
方法之前被调用,但在我的项目中并非如此。我正在 componentWillMount
中执行 fetch
操作,但在执行操作时,render
方法在 componentWillMount
完成之前被调用。这是我的 class:
class UserHomeScreen extends Component {
state = { userID: '' };
componentWillMount(){
AsyncStorage.getItem('userId').then((value) => {
this.setState({ userID: value });
const API_ENDPOINT= 'https://myserverAPI';
const userID = value;
fetch(API_ENDPOINT,{ method: "GET",
headers:{
'Authorization': 'Bearer '+ userID
}
})
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
userInfo = new UserInfo();
userInfo.updateValues(responseJson);
AsyncStorage.setItem("userInfo",JSON.stringify(userInfo),null);
backInfo = AsyncStorage.getItem("userInfo").then(value);
})
});
}
render(){
return(
<Text>hello { this.state.userID }
</Text>
)
}
}
它们以正确的生命周期顺序被调用。您的问题出在 fetch
中,因为 Fetch API returns a Promise
不是同步的。如果你在承诺中设置状态,你可以通过强制 re-render 来解决这个问题,例如
this.setState({mode = 'loading'})
API.fetch().then(this.setState({mode = 'finished'})); // pseudo code
或强制等待 Promise
。我会选择选项一并在您的渲染方法中设置一个占位符,例如
render() {
return (
this.state.mode == "loading" ? <div>"Loading..." </div> :
<div>{do your stuff with the fetched response}</div>
}