【问题标题】:Returning promise from dispatch从调度返回承诺
【发布时间】:2017-03-16 13:31:35
【问题描述】:

这是我的行动:

export function fetchNearbyUsers(user, position) {
  return (dispatch) => {
    const query = new Parse.Query(Parse.User);
    query.withinKilometers('location', createGeoPoint(position), 10);
    query.equalTo('gender', user.attributes.interest);
    query.notEqualTo('objectId', user.id);
    query.limit(15);
    return query.find().then((users) => {
      dispatch({ type: GET_NEARBYUSER_LIST, payload: users });
      return Promise.resolve();
    }).catch((error) => {

    });
  };
}

现在的问题是,当我通过 connect 映射我的调度时,为什么返回未定义。

this.props.fetchNearbyUsers(this.props.user, this.props.location).then(() => {
  this.setState({ refreshing: false });
}).catch((error) => {

});

const mapDispatchToProps = dispatch => ({
  fetchNearbyUsers: (user, position) => {
    dispatch(fetchNearbyUsers(user, position));
  },
});

当我通过上下文访问商店时,这会返回 Promise:

const { dispatch } = this.context.store;
this.setState({ refreshing: true });
dispatch(fetchNearbyUsers(this.props.user, this.props.location)).then(() => {
    this.setState({ refreshing: false });
 });

【问题讨论】:

    标签: javascript reactjs redux redux-thunk


    【解决方案1】:

    箭头函数的工作方式:

    var addOne = (arg) => arg+1;
    

    addOne 返回 arg 加 1,有一个隐含的返回 - 这是简写

    var addOne = (arg) => {
        return arg+1;
    }
    

    注意,如果在箭头函数体中使用 {},则不再有隐含返回

    所以 - 你的代码需要是

    const mapDispatchToProps = dispatch => ({
      fetchNearbyUsers: (user, position) => {
        return dispatch(fetchNearbyUsers(user, position));
      }
    });
    

    const mapDispatchToProps = dispatch => ({
      fetchNearbyUsers: (user, position) => 
        dispatch(fetchNearbyUsers(user, position))
    });
    

    const mapDispatchToProps = dispatch => ({
      fetchNearbyUsers: (user, position) => dispatch(fetchNearbyUsers(user, position))
    });
    

    【讨论】:

      【解决方案2】:

      你在用React-Thunk

      你在调度中做了什么:

      dispatch(fetchNearbyUsers(this.props.user, this.props.location)).then(() => {
          this.setState({ refreshing: false });
      });
      

      似乎是重复的,因为它可以在 reducer 中完成,为什么要返回整个承诺?

      【讨论】:

        猜你喜欢
        • 2016-06-15
        • 2017-09-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-10-02
        • 2019-08-14
        • 2016-03-09
        相关资源
        最近更新 更多