Reactjs 为什么我对样式化组件的恶意使用导致调用堆栈大小被超过

Reactjs 为什么我对样式化组件的恶意使用导致调用堆栈大小被超过,reactjs,styled-components,gatsby,Reactjs,Styled Components,Gatsby,我正在用盖茨比做一个网站。我也在使用样式化的组件 对于某个页面,设计师们以其无穷的智慧决定,某个按钮应该 1) 在桌面的页面顶部显示 2) 显示在手机页面的底部。 因为我已经深入到这个项目中了,所以我不想用绝对的方法来定位每件事。因为其他东西会坏。所以我试过这个 const SizeDetector = styled.div` height: 0px; width: 100%; background-color: ${props => {

我正在用盖茨比做一个网站。我也在使用样式化的组件

对于某个页面,设计师们以其无穷的智慧决定,某个按钮应该 1) 在桌面的页面顶部显示 2) 显示在手机页面的底部。 因为我已经深入到这个项目中了,所以我不想用绝对的方法来定位每件事。因为其他东西会坏。所以我试过这个

const SizeDetector = styled.div`
  height: 0px;
  width: 100%;
  background-color: ${props => {
                        props.detectDesktopAndTablet()
                        return 'white'
                        }
                      }
  @media (max-width: 450px) {
    background-color: ${props => {
                          props.detectMobile()
                          return 'white'
                          }
                        }
                      }
`

class ContextualFrame extends React.Component {
  constructor() {
    super();
    this.detectMobile = this.detectMobile.bind(this);
    this.detectDesktopAndTablet = this.detectDesktopAndTablet.bind(this);
    this.detectDesktopAndTablet = this.detectDesktopAndTablet.bind(this);
    this.state = {'mobile': false, 'hasMounted': false}
  }
  detectMobile() {
    this.setState({'mobile': true})
  }
  detectDesktopAndTablet() {
    console.log('here')
    this.setState({'mobile': false})
  }
  componentDidMount() {
    this.setState({'hasMounted': true})
  }
  render() {
    let {mobile, hasMounted} = this.state
    return (
      <div>
        {
          hasMounted ? (<SizeDetector detectDesktopAndTablet={this.detectDesktopAndTablet} detectMobile={this.detectMobile} />) : null
        }
        {
          mobile ? null : (<MeetPeopleButton text={'Meet The Team'} />)
        }
        {this.props.children}
        {
          mobile ? (<MeetPeopleButton text={'Meet The Team'} />) : null
        }
      </div>
    )
  }
}
detectDesktopAndTablet中控制台日志中的“here”被调用了数千次


为什么会这样?我猜这可能是由于某种特定的方式,即样式化组件或反应工作。要求提高我对React工作原理的理解

也许我已经解决了你的问题。这是因为在渲染过程中,您正在更改组件的状态,使其再次渲染,等等:

contextalframe.render()
->调用
SizeDetector.render()
->调用
detectedesktopandTablet()
->调用
setState(…)
->procs
contextalframe.render()

要解决此问题,请在设置属性之前检查属性是否相同:

detectDesktopAndTablet() {
  console.log('here')
  if(this.state.mobile !== false) this.setState({'mobile': false})
}

styled.div
来自哪里?styled.div是一个样式组件。这听起来不错。因此,重新渲染会导致更多的重新渲染。不过,我写上述内容是为了在开发过程中调整屏幕大小时提供帮助。因此无法使用您的变通方法。谢谢你的洞察力。
detectDesktopAndTablet() {
  console.log('here')
  if(this.state.mobile !== false) this.setState({'mobile': false})
}