javascript - react : how to prevent api calls in ComponentDidMount and in ComponentDidUpdate override each other

标签 javascript reactjs race-condition lifecycle fetch-api

componentDidMount 中,我使用 Redux 操作获取数据,例如:

componentDidMount() {
   let parameter = some code;
   this.props.getAction(parameter).then(r => {
     if(r.type.endsWith('SUCCESS')){
       this.setState({cList: r.payload.data.data})
     }
   }
}

然后,在 componentDidUpdate 中,当函数内的参数发生变化时,我需要再次获取数据(我正在使用 lodash):

componentDidUpdate(prevProps, prevState){
   if(!isEqual(this.props.parameter, prevProps.parameter){
     let parameter = some code;
     if(r.type.endsWith('SUCCESS')){
       this.setState({cList: r.payload.data.data})
     }
   }
}

问题在于,如果componentDidUpdate中的Promise返回的结果在componentDidMount中的Promise之前,当我在组件中更改参数时,显示的数据是错误的;它仍然显示来自 componentDidMount 的数据,而不是来自 componentDidUpdate 中的新操作调用的数据。

我希望一切都清楚。

我怎样才能避免这种情况?谢谢。

最佳答案

你可以在你的组件中保留一个实例变量 lastRequestId 来跟踪哪个 promise 正在运行,就像这样:

class MyComponent extends Component {
  constructor(props) {
    super(props);

    this.lastRequestId = null;
  }

  componentDidMount() {
    let parameter = "some code";
    this.lastRequestId = 'ON_MOUNT_REQUEST';
    this.props.getAction(parameter).then(r => {
      if(r.type.endsWith('SUCCESS') && this.lastRequestId === 'ON_MOUNT_REQUEST'){
        this.setState({cList: r.payload.data.data})
      }
    })
  } 

  componentDidUpdate(prevProps, prevState){
    if(!isEqual(this.props.parameter, prevProps.parameter)) {
      let parameter = "some code";
      this.lastRequestId = 'ON_UPDATE_REQUEST';
      this.props.getAction(parameter).then(r => {
        if(r.type.endsWith('SUCCESS') && this.lastRequestId === 'ON_UPDATE_REQUEST'){
          this.setState({cList: r.payload.data.data})
        }
      })
    }
  }
}

关于javascript - react : how to prevent api calls in ComponentDidMount and in ComponentDidUpdate override each other,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57871206/

相关文章:

javascript - 从 div 中完全删除元素

reactjs - 独立组件react和redux之间传递数据

javascript - 无法读取 ReactJS 中未定义的属性 'state' (Gatsby)

java - 多个线程从不同实例访问实例方法会导致竞争条件吗?

Golang,与本地 map 的竞争条件

javascript - 在外部 SVG 中选择元素

php - 用php json_encode传输html问题

javascript - 将 react-dropzone 与 nextjs 一起使用 - 输入类型为 "file"的多个属性在服务器渲染时卡在 false 上,如何将其设置为 true?

javascript - 如何使用 React 子元素创建 <Modal.Title> 等元素

cassandra - 如何使用 cassandra 更新处理竞争条件?