reactjs - 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();
}
解决方案
你在调度调用中调用它dispatch(setIngredients(response.data));
这个调度调用接收你从 setIngredients 返回的对象,
调度调用实际上将使用从 setIngredients 返回的操作调用您的减速器
此外,如果您尝试在setIngredients(data)
没有调度的情况下单独调用,它永远不会触发减速器,因此它不起作用
推荐阅读
- javascript - 开玩笑:只能在运行单个测试时重新模拟实现
- java - Java写入文件 - 使用类
- c# - FindViewById 返回 null(只有一个,在 OnCreate 内部和 SetContentView 之后)
- javascript - javascript 使用 appendChild 出现具有特定 ID 的事物
- vba - 引用在不同模块中创建的控制对象
- java - 继承 - 调用什么方法?
- linux - lua redis 处理错误
- python - 如何将输入矩阵拆分为子矩阵以进行并行 GPU 处理?
- amazon-dynamodb - 如何查询 DynamoDb 中的对象列表(使用 CLI)
- asp.net-mvc - 不支持关键字:“元数据”。尝试创建动态连接字符串时