如何使调度同步 [英] How to make dispatches synchronous

查看:78
本文介绍了如何使调度同步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个在按钮点击时执行的函数:-

I have an the following function that is executed on button click:-

const modelClick = async(modelcategory, modelname)=>{
        const curr_model = allModels.filter(model => model.model === modelname && model.version === version)
        console.log("curr_model= ", curr_model[0]);
        await dispatch(setModel(curr_model[0]))
        await dispatch(getModelsOfType(curr_model[0]['model category']))
        console.log("models=", models);
        let temp;
        temp = models.filter(model => model.modelname === curr_model[0]['model_type'])
        console.log("temp inside modelClick= ", temp);
}

dispatch(getModelsOfType(curr_model[0]['model category'])) :该函数查询 dynamodb 并更新全局 redux 状态 'models'.然后我想根据类型过滤模型.

dispatch(getModelsOfType(curr_model[0]['model category'])) : This function queries the dynamodb and update the global redux state 'models'. I then want to filter the models based on type.

我面临的问题是调度下面的代码在状态更新之前被执行.它给出了一个错误,说模型未定义.我想同步运行它,以便仅在模型更新后才执行过滤器行.如何实现?

THE ISSUE i am facing is that the code below the dispatch gets executed before the state gets updated. It gives an error saying models is undefined. I want to run it synchronously so that the filter line gets executed only after models is updated. How can that be achieved ?

这是动作创建函数:-

export const getModelsOfType=(modeltype)=> async(dispatch) => {
    dispatch({
        type: GET_MODELS_OF_TYPE_REQUEST
    })
        let params = {
            model_type: modeltype
        }
       axios
        .post(`${BACKEND_URL}get-models`, params, {
          headers: {
            "Content-Type": "application/json",
          },
        })
        .then((res)=>{
            console.log("DYNAMO DB RESULT= ", res.data.Items)
            dispatch({
                type: GET_MODELS_OF_TYPE_SUCCESS,
                payload: res.data.Items
            })
        })
        .catch((err) => {
            console.log("err >>", err);
            dispatch({
                type: GET_MODELS_OF_TYPE_FAIL
            })
        });
}

推荐答案

而不是在组件中分派动作.你可以做的是在第一个动作中分派第二个动作然后阻止.

Instead of dispatching the action in the component. what you can do is dispatch the second action inside the first actions then block.

export const setModel=(your arguments)=> async(dispatch) => {
  dispatch({
      type: ACTION_REQUEST
  })
     axios
      .post(// make API call)
      .then((res)=>{
          dispatch({
              type: ACTION_SUCCESS,
              payload: res
          })

          // now dispatch the second action here . 
          dispatch(getModelsOfType(your arguments))
      })
      .catch((err) => {
          console.log("err >>", err);
          dispatch({
              type: ACTION_FAILURE
          })
      });
}

这篇关于如何使调度同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆