如果您偶然发现了mobx的优点,那么您需要转向无状态解决方案,即:
用户屏幕.js
componentDidMount() {
this.getUserDetails();
}
async getUserDetails(){
await this.props.UserStore.getUserDetails('1');
}
render () {
const { isLoading, userDetails, error } = this.props.UserStore
return (<View>
{(!!isLoading)?<Text>{userDetails}</Text>:<Text>Loading</Text>}
</View>)
}
UsStur.JS
@observable userdetails = {};
@observable isLoading = false;
@observable error = {};
async getUserDetails(userID) {
this.isLoading = true;
try {
await axios.get('http://192.168.1.9/user/' + userID)
.then(response => {
console.log('returned data from api / userstore '+response.data.user);
this.userdetails = response.data.user;
this.isLoading = false;
})
.catch(error => {
console.log(error);
this.error = error
})
} catch (e) {
console.log('ERROR', e);
this.isLoading = false;
}
}
当您将数据传递到一个可观察数组中时,即@observate userdetails={};一旦promise/await完成,mobx将自动更新状态。
P.S.MOBX规则好的!!!