如何在if / else语句中将该prop作为函数执行?

时间:2019-04-09 16:09:11

标签: redux redux-thunk

如果GoogleMap DirectionService返回错误,我想更改Redux Reducer中的状态。 如果我使用react-google-maps包,并且应用程序在使用该包的组件文件中接收数据,则该应用程序如何在redux动作文件中使用redux-thunk逻辑?

componentDidMount() { 
     const DirectionsService = new google.maps.DirectionsService();
     DirectionsService.route({
            //some state
          }, (result, status) => {
            if (status === google.maps.DirectionsStatus.OK) {
              this.setState({
                directions: {...result},
                markers: true
              })
            } else {
              this.props.HOW_TO_EXECUTE_THIS_PROP?;
            }
          });
}

const mapDispatchToProps = (dispatch) => {
    return {
        HOW_TO_EXECUTE_THIS_PROP?: () => dispatch(actions.someAction()),
    }
}

1 个答案:

答案 0 :(得分:0)

通常,您将能够简单地调用传入的prop方法。因此,如果您的代码显示为:

const mapDispatchToProps = (dispatch) => {
     return {
         propToExecute: () => dispatch(actions.someAction()),
     }
}

...然后您将在componentDidMount内部将其称为:

this.props.propToExecute();

但是,由于我们正在使用ES6,因此请正确格式化其格式,请:

const mapDispatchToProps = dispatch => ({
     propToExecute: () => dispatch(actions.someAction())
})