Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/384.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript React HOC组件调用异步操作,使用componentWillMount触发两次?_Javascript_Reactjs_Ecmascript 6 - Fatal编程技术网

Javascript React HOC组件调用异步操作,使用componentWillMount触发两次?

Javascript React HOC组件调用异步操作,使用componentWillMount触发两次?,javascript,reactjs,ecmascript-6,Javascript,Reactjs,Ecmascript 6,我有这段代码 export default function CheckHasSentGift(TransformedComponent) { @connect(state=>state.global,{fetchGift}) class WithRedirect extends Component { componentWillMount() { this.props.fetchGift('sent') } render() {

我有这段代码

export default function CheckHasSentGift(TransformedComponent) {
  @connect(state=>state.global,{fetchGift})
   class WithRedirect extends Component {
    componentWillMount() {
      this.props.fetchGift('sent')
    }

    render() {
      this.props.sentGiftId && 
      !this.props.location.pathname.includes('sent') && 
      return <Redirect to={`/app/gift/${this.props.sentGiftId}/sent`} />

      return <TransformedComponent { ...this.props } />
    }
  }

  return WithRedirect
}
导出默认函数CheckHasSentGift(TransformedComponent){
@连接(state=>state.global,{fetchGift})
使用重定向扩展组件初始化{
组件willmount(){
this.props.fetchGift('sent')
}
render(){
this.props.sentGiftId&&
!this.props.location.pathname.includes('sent')&&
返回
返回
}
}
用重定向返回
}
这是我的路线

<Route exact path='/app' component={CheckHasSentGift(App)} />

我做重定向没有问题,它工作了,但我在我的网络选项卡中看到了两个对fetchGift api的调用。然后,我在render方法中进行调试

render() {
  //this.props.sentGiftId && 
  //!this.props.location.pathname.includes('sent') && 
  //return <Redirect to={`/app/gift/${this.props.sentGiftId}/sent`} />

  console.log('check render')

  return <h1>test</h1>
  //return <TransformedComponent { ...this.props } />
}
render(){
//this.props.sentGiftId&&
//!this.props.location.pathname.includes('sent')&&
//返回
console.log('check render')
回归试验
//返回
}

而且渲染只渲染一次,为什么在重定向后componentWillMount可以触发两次?

实际上
componentWillMount
从React.v16.3开始就不推荐使用,最好使用它开始提取数据

而且渲染只渲染一次,为什么组件willmount可以 重新定向后发射两次

将您的console.log放到
组件willmount
以查看是否调用了两次


还要确保第一个请求不是浏览器将触发的描述服务器之间通信的请求。您可以在浏览器“开发人员工具”的“网络”选项卡中进行检查。

我认为react团队在此专门解决了此问题:。还有这里:。我认为理想的做法是在构造函数MethodTested componentDidMount中进行异步调用,触发两次,然后放入构造函数,工作正常。componentDidMount在调用第一次渲染后触发,为什么要将其用于异步调用?@JamieAden如果没有完整的示例,很难说出为什么要创建两次此组件。文档中说,这是启动异步调用的最佳位置。componentWillMount可能会导致一些内存泄漏(例如,在服务器端渲染时调用它)。