1

在 redux 中,我有一个 (count, remote Count) 我将其默认设置为 0 !

主要思想是比较计数是否等于远程计数我想发送一个锁定应用程序的动作“真/假”

在主屏幕从 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);
      }
    });
}
4

2 回答 2

1

使用渲染获取更新的计数。componentDidMount 在组件第一次挂载时运行。将计数保存在组件中redux storemapToState

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);
    }
  }
}
于 2020-04-29T14:26:19.833 回答
0

您可以使用dispatch asyncredux thunk 来使用该功能。

  1. 安装 redux thunk。

  2. 用作商店内的中间件。

import thunk from 'redux-thunk';
import rootReducer from './reducers';

const store = createStore(rootReducer, applyMiddleware(thunk));
  1. 使用它来调度异步操作。
return async dispatch=>{ let res= await authLogin(data)}
于 2020-05-02T16:41:20.770 回答