【发布时间】: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