首页 > 解决方案 > Redux 操作可以在 React 中调度和返回一些东西吗

问题描述

我已经正确设置了我的 redux:存储、操作、reducers,我已经将状态映射到道具等,并且我正在使用 redux thunk。

这就是我当前的操作:

在此处输入图像描述

我通常在我的组件中使用这样的操作,它工作得很好:

this.props.addCars(newCar)

有时我想添加一辆新车,并在下一行使用 this.props.cars 对新数据做一些事情

This.props.cars没有显示我最近添加的汽车,但使用了 Promise,或者像这样等待不起作用

await this.props.addCars(newCar)

所以我想知道是否有办法让我的动作调度并返回数据响应。

标签: reactjsredux

解决方案


您需要等待来自 axios 的响应,然后分派结果和返回。像这样的东西。

 export async function addCars(car){
  var result = await axios.post('http://localhost:8000/api/cars', car)
               .then((resp)=>
                {
                  return resp.data
                }


  dispatch({type: ADD_CAR, payload: result});
  return result;
}

推荐阅读