首页 > 解决方案 > Redux thunk,用 axios 初始化成分,问题

问题描述

嘿伙计们,我真的很想了解一些东西。我做了一个 react js 课程,我无法理解我们使用 redux thunk 从数据库中初始化汉堡成分的部分。

我的问题是,当我不在任何地方调用它时,如何调用 setIngredients 函数?因为当我在 componentDidMount 中调用 setIngredients 时,它不起作用,但是如果我调用 initIngredients,它会起作用。它是在 initIngredients 函数中调用的吗?你能向我解释一下这段代码是如何工作的吗?

/actions/burgerBuilder.js

export const setIngredients = (ingredients) => {
  return {
    type: actionTypes.SET_INGREDIENTS,
    ingredients: ingredients,
  };
};

export const initIngredients = () => {
  return (dispatch) => {
    axios
      .get("https://.........json")
      .then((response) => {
        dispatch(setIngredients(response.data));
      })
      .catch((error) => {
        dispatch(fetchIngredientsFailed());
      });
  };
};

/reducers/burgerBuilder.js

...
case actionTypes.SET_INGREDIENTS:
      return {
        ...state,
        ingredients: action.ingredients,
        error: false,
      };
...

在主容器中,mapDispatchToProps 中的 BurgerBuilder.js 我返回了这个对象

onInitIngredients: () => dispatch(burgerBuilderActions.initIngredients()),

当我在上面调用时,在 componentDidMount 中是这样的:

componentDidMount() {
    console.log(this.props);
    this.props.onInitIngredients();
  }

标签: reactjsreact-reduxredux-thunk

解决方案


你在调度调用中调用它dispatch(setIngredients(response.data)); 这个调度调用接收你从 setIngredients 返回的对象,

调度调用实际上将使用从 setIngredients 返回的操作调用您的减速器

此外,如果您尝试在setIngredients(data)没有调度的情况下单独调用,它永远不会触发减速器,因此它不起作用


推荐阅读