简体   繁体   English

this.props不是componentDidUpdate()中的函数

[英]this.props is not a function in the componentDidUpdate()

I'm facing a weird problem, there's probably a simple thing I didn't noticed but I'm not able to pass through this bug. 我面临一个奇怪的问题,可能有一件简单的事情我没有注意到,但我无法通过此错误。 Here's my case: 这是我的情况:

In the child, a counter is updated onClick. 在子级中,计数器会更新onClick。 What I'm trying to do is fire a props function to togle the state of the parent. 我想做的是触发一个props函数来切换父级的状态。

In the child: 在孩子中:

  componentDidUpdate(){
    if(this.state.counter === 3){
      return this.props.isFullBackgroundHomePage();
    }else{
      return;
    }
  } 

In the parent: 在父级中:

  renderHomePage = () => {
    if(this.state.isHomePage
      && this.state.home_page !== null){
      return (
        <HomePage
          isFullBackgroundHomePage={this.isFullBackgroundHomePage}
          triggerSeeAllSection={this.triggerSeeAllSection}
          {...this.state}
        />
      )
    }else{
      return null;
    }
  }

  isFullBackgroundHomePage = () => {
    this.setState({
      isFullBackgroundHomePage: !this.state.isFullBackgroundHomePage
    })
  }


Now, this is what appears in the browser when the counter is at 3: 现在,这是计数器在3时在浏览器中显示的内容:

TypeError: this.props.isFullBackgroundHomePage is not a function

Link to the browser log: https://ibb.co/vcMW3wL 链接到浏览器日志: https : //ibb.co/vcMW3wL

In

<HomePage
  isFullBackgroundHomePage={this.isFullBackgroundHomePage}
  triggerSeeAllSection={this.triggerSeeAllSection}
  {...this.state}
/>

you are overwriting prop isFullBackgroundHomePage using {...this.state} thus its not a function anymore rather a true/false boolean value at the consuming component. 您正在使用{...this.state}覆盖prop isFullBackgroundHomePage因此它不再是一个函数,而是使用组件上的true / false布尔值。 In your consuming component if you need both, you should rename state or prop value. 如果您同时需要使用组件,则应重命名状态或属性值。

Very common issue unintentionally overwriting props using spread, gets the best of developer musing around what the heck is going on but to avoid such issues, consider using separate naming for function and state value to separate concerns. 非常常见的问题是无意识地使用价差覆盖了道具,这使开发人员可以更好地思考到底发生了什么,但要避免此类问题,请考虑对功能和状态值使用单独的命名方式来分离关注点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM