我在react组件中有一个方法lookupComplete,它调用操作checkIfAssign,我需要等待响应,并在此方法中依赖于此响应触发器的另一个方法。但是收到Promise {<pending>} "result"。如何等待直到解决此问题?

零件:

export class Test extends Component {
  ....

  lookupComplete = (tagId = this.state.tagId) =>
    this.setState({tagId}, () => {
      let result = this.props
        .checkIfAssign(this.state.tagId, this.props.accessToken)

    result.status
      ? this.triggerTransition(transitions.ClickCheckTag)
      : this.triggerTransition(transitions.Test)
    })
}

export const mapDispatchToProps = dispatch => ({
  checkIfAssign: (tagId, accessToken) =>
    dispatch(TagAssignmentActions.checkTagAssignment(tagId, accessToken)),
})


行动:

export const checkTagAssignment = (tagId, token) => async dispatch => {
  dispatch({
    type: TagAssignmentActionTypes.TagAssignmentChanged,
  })

  let status, assignee, response
  try {
    response = await DeviceApi.checkTagAssignment(tagId, token)

    assignee = response.result.assignee
    status = response.result.status
  } catch (e) {
    if (e && e.status === httpStatusCode.notFound)
      status = TagStatus.NotFound
  }

  dispatch({
    type: TagAssignmentActionTypes.TagAssignmentChanged,
    status,
    assignee,
    response,
  })
  console.log(response, 'response')
  return response
}

最佳答案

如果要await,则应将函数设置为async

lookupComplete = async (tagId = this.state.tagId) =>
...

  let result = await this.props
    .checkIfAssign(this.state.tagId, this.props.accessToken)


但是,这是一个不好的模式。正确的会从您的应用程序状态读取status。如您所见,您的操作将在此处更新应用程序状态:

dispatch({
  type: TagAssignmentActionTypes.TagAssignmentChanged,
  status,
  assignee,
  response,
})


如果您正确执行redux,则Test组件可能被connect()还原。在您的mapStatesToProps中,将status的值从应用程序状态传递到Test组件props

const mapStateToProps = state => ({
  status: state.myNamespaceForTaskAssignment.status,
});


然后在getDerivedStateFromProps(nextProps, prevState)中进行检查:

nextProps.status
  ? this.triggerTransition(transitions.ClickCheckTag)
  : this.triggerTransition(transitions.Test)


或类似的东西。

关于javascript - 来自React组件的异步/等待调用 Action ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50295036/

10-10 00:50