反应-无法在挂钩组件中分派动作

时间:2020-08-21 10:18:06

标签: react-redux react-hooks

在功能组件的useffect挂钩中使用调度, 下面的代码显示错误页面,如下所示; enter image description here

组件:

  import { GetParks } from "../../../redux/actions/survey_actions"
...
function BarcodeGenerator(props) {
  const dispatch = useDispatch();

  useEffect(() => {
    dispatch(props.GetParks());
  }, []);

动作:

export const GetParks = (Id) => async (dispatch, getState) => {
  try {
    const response = await axiosHelper.get("api/survey/GetParks", {
      params: {
        Id,
      },
    });
    debugger;
    response = response.data;
    if (response.status !== ResponseStatus.SUCCESS) {
      dispatch({
        type: GET_PARKS,
        payload: [1, 4555, 34],
      });
    }
  } catch (error) {
    catchCallback(error);
  }
};

const _getParks = (data) => ({
  type: GET_PARKS,
  payload: data,
});

如何正确地将动作分配给减速器

1 个答案:

答案 0 :(得分:0)

操作必须是一个普通对象,如错误说明中所述。例如。可以直接按原样使用分派:

if (*statement*) {
  dispatch({
    action: DO_SMTH,
    payload: true
  })
}

,或者如果您想编写干净的可重用代码,则使操作创建者返回相等的对象:

if (*statement*) {
  dispatch(doSmth(true));
}
function doSmth(toggle) {
  return ({
    action: DO_SMTH,
    payload: toggle
  })
}