【问题标题】:Redux thunk, initialize ingredients with axios, questionRedux thunk,用 axios 初始化成分,问题
【发布时间】:2021-01-04 12:02:45
【问题描述】:

嘿,伙计们,我真的很想了解一些事情。我做了一个 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();
  }

【问题讨论】:

    标签: reactjs react-redux redux-thunk


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2016-09-22
      • 2020-02-22
      • 1970-01-01
      • 1970-01-01
      • 2019-04-08
      • 2018-12-02
      • 2021-11-24
      • 1970-01-01
      • 2021-06-22
      相关资源
      最近更新 更多