首页 > 解决方案 > Redux 返回未定义的承诺

问题描述

我一直试图弄清楚 Redux。目前我所有的“绘画”道具都是一个未定义价值的承诺:

在页面组件中:

componentDidMount = () => {
  this.props.setPaintingToProps(paintingId);
}

...

const mapStateToProps = state => {
  return {
    painting: state
  };
};

const mapDispatchToProps = dispatch => {
  return {    
    setPaintingToProps: paintingId => {
      dispatch({ type: "SET_PAINTING", id: paintingId });
    }
  };
};

在减速机中:

case "SET_PAINTING":
  paintingService.getDetails(action.id).then(data=>{
    return {...state,
      ...data}
})
break;

reducer 方法运行并且data是正确的,但在状态下它是Promise {<resolved>: undefined}

在此先感谢您,如果需要更多信息来解决此问题,请询问。

标签: javascriptreactjsreduxfrontendprop

解决方案


您应该使用中间件进行异步调用,例如 redux-thunk 来创建异步操作,然后调度您的数据

export const setPaintingToProps = (paintingId) =>
  (dispatch) => {
    paintingService.getDetails(paintingId).then(data => {
      dispatch({ type: "SET_PAINTING", payload: data });
    })
  };

const mapDispatchToProps = dispatch => {
  return {    
    setPaintingToProps: paintingId => dispatch(setPaintingToProps(paintingId));
    }
  };
};

case "SET_PAINTING":
    return {...state,
      action.payload}
})
break;

请让我知道这对你有没有用


推荐阅读