React Native 在继续之前不等待 API 的响应

React native not waiting for response from API before continuing

我刚开始玩 React Native,我遇到一个问题,即函数在继续之前不等待响应。

所以在 Chrome 我的控制台日志显示:

userStore

this state contents

returned data from api / userstore [object Object]

基本上会执行 getUserDetails,在调用 api 时运行 setData 函数,并在返回 api 结果之前完成。

我希望 getUserDetails 函数在调用 setData 之前完成。

网上看了看资源,一头雾水。我正在使用的代码如下(为了便于阅读 nb,已将其删除。我正在使用 mobx)

UserScreen.js

constructor (props) {
    super(props);
    this.state = {
        data: null
    };
}

async componentDidMount() {
  this.props.commonStore.setLoading(true);
  await this.props.userStore.getUserDetails('1');        
  this.setData();
  this.props.commonStore.setLoading(false);   
}

setData() {
    this.setState({
      userDetails: this.props.userStore.userDetails
  });
  console.log('userStore' + this.props.userStore.userDetails)
  console.log('this state contents '+ this.state.userDetails);
}

render () {
  if(this.props.commonStore.isLoading===false) {
    return (<View><Text>Ready!!</Text></View>)
  }else{}
    return (<View><Text>Loading</Text></View>)
  }
}

UserStore.js

@action getUserDetails = (userID) => {
    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;
    }).catch(error => {
      console.log(error);
      this.error = error
    })   }

谢谢

如果您偶然发现了 Mobx 的美妙之处,则需要转向无状态解决方案,即:

UserScreen.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>)
}

UserStore.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;
            }
        }

当您将数据传递到可观察数组时,即@observable userdetails = {};一旦 promise / await 完成,Mobx 将自动更新状态。

P.S。 Mobx 规则 OK!! :o)