轮询API,直到使用React将任务状态设置为“COMPLETELY_SIGNED”

问题描述 投票:1回答:1

我有一个fetch函数和update函数来执行任务操作。当我调用update函数时,taskId被更改,所以我需要检查任务状态是否为'COMPLETELY_SIGNED'以加载下一个组件。

async process({action, request}, dispatch, done) {
const {form} = action.payload

try {
  const params = {
    taskId: form.taskId,
    password: form.password
  }
  dispatch(resetTaskFormErrors())
  const response = await request({
    method: 'POST',
    url: 'task/update',
    params: params,
    data: form.taskRequest
  })
  dispatch(updateTaskSuccess(response.data))
  dispatch(fetchTask(response.data.id)) }

所以我使用新的taskID调用fetch函数来检查任务状态是否为“COMPLETELY_SIGNED”。不幸的是,任务状态不会很快改变,因此我需要轮询fetch API以进行检查,直到状态变为“COMPLETELY_SIGNED”。

更新任务时,响应将具有editor对象。这用于检查任务是否在componentWillRecieveProps中更新

所以我决定在componentWillRecieveProps处理道具变化

UNSAFE_componentWillReceiveProps(nextProps) {
    if (!isEqual(nextProps.buyerOTPForm, this.state.task)) {
      if (nextProps.buyerOTPForm.otpData.editor &&
        nextProps.buyerOTPForm.status !== 'COMPLETELY_SIGNED') {
        this.props.fetchTask(nextProps.buyerOTPForm.otpData.id)
      }
      else if (nextProps.buyerOTPForm.otpData.editor &&
        nextProps.buyerOTPForm.status === 'COMPLETELY_SIGNED') {
        this.setState({
          isApproved: true
        })
      }
      this.setState({
        task: nextProps.buyerOTPForm.otpData,
        errors: nextProps.buyerOTPForm._errors,
        ...nextProps.signingSuccess ? {
          isSigning: false
        } : {},
        ...nextProps.rejectingSuccess ? {
          isRejecting: false
        } : {}
      }, () => {
        this.propertyPriceValidation()
      })
    }   }

我在这里得到无限循环。我怎么可能解决我的问题?

reactjs react-redux polling
1个回答
1
投票

问题是你没有将当前道具与之前的道具进行比较并直接进行setState。您需要使用以前的道具检查当前道具,如果它们不相等,则执行setState。以下代码应该有效

 UNSAFE_componentWillReceiveProps(nextProps){
  if(nextProps.buyerOTPForm.otpData !== this.props.buyerOTPForm.otpData){
  if (nextProps.buyerOTPForm.otpData.editor &&
    nextProps.buyerOTPForm.status !== 'COMPLETELY_SIGNED') {
    this.props.fetchTask(nextProps.buyerOTPForm.otpData.id)
  }
  else if (nextProps.buyerOTPForm.otpData.editor &&
    nextProps.buyerOTPForm.status === 'COMPLETELY_SIGNED') {
    this.setState({
      isApproved: true
    })
  }
  this.setState({
    task: nextProps.buyerOTPForm.otpData,
    errors: nextProps.buyerOTPForm._errors,
    ...nextProps.signingSuccess ? {
      isSigning: false
    } : {},
    ...nextProps.rejectingSuccess ? {
      isRejecting: false
    } : {}
  }, () => {
    this.propertyPriceValidation()
  })
}
}

它自己说的方法是不安全的,所以每当你的组件收到新的道具时,这个方法就会被调用,而且这个方法无缘无故地被调用两次,这就是为什么这是不安全的。当你想在这个方法中做setState以避免无限循环时,你需要总是用以前的道具检查当前道具。

© www.soinside.com 2019 - 2024. All rights reserved.