【发布时间】:2021-08-10 20:04:43
【问题描述】:
我有一个在单击按钮时执行的以下函数:-
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'。然后我想根据类型过滤模型。
我面临的问题是调度下面的代码在状态更新之前被执行。它给出了一个错误,说模型未定义。我想同步运行它,以便仅在更新模型后才执行过滤器行。怎么实现?
这里是动作创建函数:-
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
})
});
}
【问题讨论】:
-
在您的
getModelsOfType动作中,您可以执行await axios.post...或return axios.post...,但我认为models仍将是stale closure,因此可以使用效果或从您的动作中返回新模型.
标签: reactjs react-redux redux-thunk dispatch