我正在学习React,并且对自己所做的事情有疑问。 从另一个动作中调用一个动作是否正确?做这样的事情是最好的选择吗?
import * as types from "../types/actionTypes";
import * as consumptionApi from "../../utils/api/consumptionApi";
import * as taskApi from "../../utils/api/taskApi";
import * as taskActions from "../actions/taskActions";
export function loadProjectConsumptionSuccess(consumptions) {
return { type: types.LOAD_PROJECT_CONSUMPTION_SUCCESS, consumptions };
}
export function loadProjectConsumption(projectId) {
return async function(dispatch, getState) {
try {
let tasks = await taskApi.getTasksByProjectId(projectId);
dispatch(taskActions.loadTasksByProjectSuccess(tasks));
tasks = getState().tasks;
const consumptions = await consumptionApi.getProjectConsumption(tasks);
dispatch(loadProjectConsumptionSuccess(consumptions));
} catch (error) {
console.log(error);
throw error;
}
};
}
答案 0 :(得分:0)
await
之后调度动作没有错。实际上,很长一段时间以来,它一直是首选方法,尤其是在代码变化不大的情况下。
进行过程中发现,您经常需要进行更改,而这并不是最灵活的方法。人们现在似乎要做的就是这个
// actions.js
export const retrieveData = () => () => fetch(`/url`).then(d => d.json())
export const populateData = (data) => ({ type: 'MODULE_POPULATE_DATA', data })
// inside the component
const dispatch = useDispatch()
useEffect(() => {
const loadData = async () => {
const { data } = await dispatch(retrieveData())
dispatch(populateData(data))
}
loadData()
}, [])
这另一种方法导致一定程度的代码重复(这很好),但是可以访问组件内部的所有内容:道具,引用,状态,记忆值等,而无需做任何奇怪的事情来传递它们。 / p>