在 React 应用程序中通过 redux 调用 API 不起作用
Calling API via redux in react app does not work
我正在使用 MERN 堆栈构建 Web 应用程序并使用 redux 作为状态管理。我现在正在尝试使用我的 API 从 mongoDB 加载数据并在设置为反应状态之前存储到 redux 中。当直接从 React 应用程序调用带有 getShop() 函数的 api 时,数据以 React 状态存储并显示在应用程序中。但是,当我尝试按照以下代码通过 redux 使用它时,它不起作用。没有错误,只是没有加载任何信息。
操作:
load : () => {
let thunk = (dispatch) => {
api.getShops()
.then(res => {
let barbershops = res.data
dispatch(barberFactory.set(barbershops))
})
}
return thunk
},
从 React 应用调用:
function mapDispatchToProps(dispatch){
return {
loadBarber : () => {
dispatch(barberFactory.load)
},
}
}
函数在 componentDidMount() 调用
需要调用您的 load
函数才能 return 内部操作,即
dispatch(barberFactory.load())
我正在使用 MERN 堆栈构建 Web 应用程序并使用 redux 作为状态管理。我现在正在尝试使用我的 API 从 mongoDB 加载数据并在设置为反应状态之前存储到 redux 中。当直接从 React 应用程序调用带有 getShop() 函数的 api 时,数据以 React 状态存储并显示在应用程序中。但是,当我尝试按照以下代码通过 redux 使用它时,它不起作用。没有错误,只是没有加载任何信息。
操作:
load : () => {
let thunk = (dispatch) => {
api.getShops()
.then(res => {
let barbershops = res.data
dispatch(barberFactory.set(barbershops))
})
}
return thunk
},
从 React 应用调用:
function mapDispatchToProps(dispatch){
return {
loadBarber : () => {
dispatch(barberFactory.load)
},
}
}
函数在 componentDidMount() 调用
需要调用您的 load
函数才能 return 内部操作,即
dispatch(barberFactory.load())