Javascript 如何等待行动的发出?

Javascript 如何等待行动的发出?,javascript,reactjs,react-native,redux,react-redux,Javascript,Reactjs,React Native,Redux,React Redux,在redux中,我有一个(计数,远程计数) 我在默认情况下将两者都设置为0 主要的想法是比较计数是否等于远程计数,我想发送一个锁定应用程序的操作'true/false' 在主屏幕中,从API获取远程计数,然后将其保存在redux存储中,保存良好 但是我有一个if语句,它检查count==remote count,然后锁定应用程序 所以这个语句在我保存远程计数之前调用,我想虽然我在then()中添加了它 主屏幕 getRemoteCount = async () => { try

在redux中,我有一个(计数,远程计数) 我在默认情况下将两者都设置为0

主要的想法是比较计数是否等于远程计数,我想发送一个锁定应用程序的操作'true/false'

在主屏幕中,从API获取远程计数,然后将其保存在redux存储中,保存良好

但是我有一个if语句,它检查count==remote count,然后锁定应用程序

所以这个语句在我保存远程计数之前调用,我想虽然我在then()中添加了它

主屏幕

  getRemoteCount = async () => {
    try {
      let response = await API.get('/number/subsribtion');
      let remoteCount = response.data.number;
      this.props.saveRemoteCount(remoteCount); // it's saved the remote count! 
    } catch (err) {
      console.log(err);
    }
  };




 componentDidMount() {
    const {remoteCount, count} = this.props;
    this.getRemoteCount().then(() => {
      if (count == remoteCount) {
        console.log('count', count); 
        console.log('remoteCount', remoteCount);//it's log 0!! so the next line invoke!
        this.props.isAppLock(true);
      }
    });
}

使用“渲染”获取更新的计数。componentDidMount在组件首次装载时运行。将计数保存在组件中的
redux store
mapToState

class C {
  getRemoteCount = async () => {
    try {
      let response = await API.get("/number/subsribtion");
      let remoteCount = response.data.number;
      this.props.saveRemoteCount(remoteCount); // it's saved the remote count!
    } catch (err) {
      console.log(err);
    }
  };
  componentDidMount() {
    this.getRemoteCount();
  }
  render() {
    const { remoteCount, count } = this.props;
    if (count == remoteCount) {
      console.log("count", count);
      console.log("remoteCount", remoteCount); //it's log 0!! so the next line invoke!
      this.props.isAppLock(true);
    }
  }
}

您可以使用redux thunk使用
dispatch async
函数

  • 安装redux thunk

  • 用作存储区内的中间件

  • 使用它来调度异步操作

  • iu u正在用redux更新为什么您希望计数i大于???这个.getRemoteCount()。然后(()您的redux将更新计数,使用该计数..在renderWell中,我已经在redux存储中保存了计数“第一次为0”和远程计数0,因此在渲染方法中不会等待
    getRemoteCount()
    完成并更新远程计数,因此实际上将调度
    .isAppLock(true)
    这就是我在
    then()中添加if语句的原因
    我想在远程计数从0更新到30之后,例如,然后检查并执行其他操作,你明白这一点吗?我可以通过将初始状态下的
    remoteCount
    设置为大于0的数字来解决问题,这样它就不会发送任何操作,因为count!=remoteCount!但我想了解它为什么不以这种方式工作?我不知道请参阅拧入元件的目的。除非你用它来阻止副作用。很高兴你能解决它
    import thunk from 'redux-thunk';
    import rootReducer from './reducers';
    
    const store = createStore(rootReducer, applyMiddleware(thunk));
    
    return async dispatch=>{ let res= await authLogin(data)}