【问题标题】:React redux dispatching action synchronously同步响应 redux 调度动作
【发布时间】:2021-01-01 20:59:23
【问题描述】:

我正在尝试借助我的 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));

然后在成功派发一个改变reducer状态的类型

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);"仍然给我假,虽然状态已经更新为真,这就是为什么我的输入框没有呈现

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

【问题讨论】:

  • 我认为您可能需要查看有关组件生命周期的反应文档。你能提供一个Minimal, Complete, and Reproducible 代码示例吗? modal.modal.showotpbox 是什么,它来自哪里,以及它的更新内容是什么?
  • 对最后一节进行了一些更新...看看是否有帮助? @DrewReese
  • 商店更新是异步的,您无法在那里获得正确的值。由于您已经在为 showotpbox:true 更新存储中的值,因此您可以直接从存储中读取值。它会起作用,您无需等待。
  • 好的,好的。是的,你的“状态”modal 来自渲染周期,动作被分派包含了modal 的“副本”,用于该函数执行的生命周期,它不会在函数中间更新。当modal.show 变为true 时,setshowotpbox(true); 的预期行为是什么?您是否尝试过 useEffect 来实现这种“反应性”效果?
  • 嗯 wells store.subscribe 为我工作!!

标签: javascript reactjs redux react-redux


【解决方案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));
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-13
    • 1970-01-01
    • 2019-02-03
    • 1970-01-01
    • 1970-01-01
    • 2021-10-14
    • 1970-01-01
    • 2020-09-10
    相关资源
    最近更新 更多