Javascript React类将过时的道具传递给子无状态组件

Javascript React类将过时的道具传递给子无状态组件,javascript,reactjs,typescript,Javascript,Reactjs,Typescript,我的父组件表示一个表单。 填写表单的用户可以访问表单中的信息,这些信息在更新某些字段时会实时更新。 我遇到的问题是。在其中一次更新中,当我们获取新数据并将其随机传递给孩子时,孩子有时会收到过时的道具。来自上一个请求。 结构是这样的 export class Form extends React.Component<Props, State> { fetchUpdates = async (payload) => { this.setState({ isLo

我的父组件表示一个表单。 填写表单的用户可以访问表单中的信息,这些信息在更新某些字段时会实时更新。 我遇到的问题是。在其中一次更新中,当我们获取新数据并将其随机传递给孩子时,孩子有时会收到过时的道具。来自上一个请求。 结构是这样的

export class Form extends React.Component<Props, State> {

  fetchUpdates = async (payload) => {
 
      this.setState({ isLoadingUpdates: true })
      await Service.getUpdates(payload)
        .then(response => {
          this.setState({ isLoadingUpdates: false, updates: response.data })
        })
        .catch(({ data: errors }) => this.setState({ isLoadingUpdates: false }))
    }
  }

  render () {
      const {
      updates,
      isLoadingUpdates,
    } = this.state


              <FormCombobox
                onChange={this.fetchUpdates}
                md={10}
                name="field"
                id="field"
                label="Field"
                onMenuOpen={() => forceCheck()}
                openMenuOnClick
                selectRef={this.itemSelect}
                value={values.item}
                options={itemOptions || []}
              />

    <Info
      data={updates}
      errorMessage={this.state.updatesError}
     />

  }

}
导出类表单扩展React.Component{
fetchUpdates=async(有效负载)=>{
this.setState({isLoadingUpdates:true})
等待服务。获取更新(有效负载)
。然后(响应=>{
this.setState({IsLoadingUpdate:false,updates:response.data})
})
.catch(({data:errors})=>this.setState({isLoadingUpdate:false}))
}
}
渲染(){
常数{
更新,
IsloadingUpdate,
}=这个州
forceCheck()}
openmenonclick
selectRef={this.itemSelect}
value={values.item}
选项={itemOptions | |[]}
/>
}
}

它不是每次都发生,而是在表单第一次更新时或在以下更新之一时,容器接收到以前的请求响应数据时随机发生。如何阻止父级传递过时数据?

这里的问题是,当多次调用
fetchUpdates
时,由于网络延迟,它会出现故障。假设调用了三次
fetchUpdates
,完成请求分别需要5、2和4秒。在这种情况下,您可以看到第二个请求在第一个请求之前调用
setState
。结果,info组件在第二个值之后传递第一个值。这就是为什么它是间歇性的

在这里使用wait没有帮助,因为
fetchUpdates
函数调用彼此独立

还有一件事,我注意到您有
IsLoadingUpdate
。但代码中的任何地方都没有使用它。而且呢,

if (!this.state. isLoadingUpdates) {
await Service.getUpdates(payload)
        .then(response => {
          this.setState({ isLoadingUpdates: false, updates: response.data })
        })
        .catch(({ data: errors }) => this.setState({ isLoadingUpdates: false }))
}

不起作用,因为这意味着当网络呼叫正在进行时,您将错过按键


我建议对输入使用去盎司。您可以在这里找到如何进行去噪:

代码看起来不错。需要考虑的一些事情:1。如果您使用的是
PureComponent
React.memo
,则应确保
更新
始终是新对象(而不是修补对象)。2.在您的代码中显示:
this.state.updateError
请确保在获得新数据时重新计算该值。额外提示:因为您使用的是wait,所以使用try/catch块更容易。