同步反应redux调度动作

时间:2020-09-15 06:15:15

标签: javascript reactjs redux react-redux

我试图借助redux状态在按钮上设置条件,代码如下

{showotpbox == true ? (
            <IonItem>
              <IonLabel position="stacked">OTP</IonLabel>
              <IonInput
                type="number"
                onIonChange={(e) => handleChangeOtp(String(e.detail.value))}
              />
            </IonItem>
          ) : (
            ""
          )}

其中showotpbox是一个反应挂钩状态,该状态最初设置为false,现在在单击显示“ GET OTP”的按钮后,我调度了一个动作

let data = { email };
await dispatch(requestOTP(data));

然后在成功调度后,该类型会更改减速器的状态

export const requestOTP = (data: any) => (dispatch: any) => {
  console.log('requesting')
  dispatch({ type: "LOADING", payload: true });
  console.log(data);
  axios
    .post("http://localhost:4000/request_otp", data)
    .then((res) => {
      console.log(res)
      if (res.data.status == 200) {
        dispatch({type:'SHOW_OTP_BOX'})
      } 
    })
    .catch((err) => {
      dispatch({ type: "LOADING", payload: false });
      dispatch(errorActions());
    });
};

反过来更新我的模态化约简中的状态

case 'SHOW_OTP_BOX':
return {...state,showotpbox:true}

但是我看到该功能是某种原因导致的异步操作

const modal = useSelector((state: RootState) => {
return {show: state.modal.showotpbox };
});
const getotp = async () => {
    let data = { email };
    await dispatch(requestOTP(data));
    console.log(modal.show);
    if (modal.show == true) {
      setshowotpbox(true);
    }
  };

“ console.log(modal.show);”尽管状态已更新为true,但仍然给我错误,这就是为什么我的输入框无法呈现

我尝试在getotp函数中使用async await来等待操作完成,但这似乎不起作用

1 个答案:

答案 0 :(得分:1)

由于调度是异步的,您必须在更新回调函数后立即处理商店更新。

var store = createStore(); // Redux store if it is created it should return store else it should create store and return
var storeUnsubscribe = store.subscribe(handleStoreChange);
function handleStoreChange() {
   console.log(state.modal.show);
    if (state.modal.show == true) {
      setshowotpbox(true);
    }
}
const modal = useSelector((state: RootState) => {
  return {show: state.modal.showotpbox };
});
const getotp = async () => {
    let data = { email };
    await dispatch(requestOTP(data));
};