React.JS中的无效Hook调用

时间:2019-09-18 08:05:29

标签: reactjs react-hooks react-lifecycle-hooks

long

此行import React, {Component, useState, useEffect} from 'react'; import {connect} from 'react-redux'; import BigHeader from './bigHeader'; import SmallHeader from './smallHeader'; function isSmall() { if(this.windowWidth < 1307){ return true; } return false; } const [windowWidth, setWindowWidth] = useState(window.innerWidth); function determineWidth() { const width = window.innerWidth; setWindowWidth(width); isSmall(width); } useEffect(() => { window.addEventListener("resize", determineWidth); return function() { window.removeEventListener("resize", determineWidth); } }) class Header extends Component { render() { return this.isSmall() ? <SmallHeader/> : <BigHeader/> } } // export default connect(mapStateToProps, page); export default Header; 出现错误

我正在尝试在屏幕<1307时返回移动/较小的标题,而在屏幕上方时返回不同的标题。

4 个答案:

答案 0 :(得分:1)

如果要使用挂钩(包括自定义挂钩),则必须从功能组件中使用它们,这是带有自定义挂钩的代码,并且Header是功能组件而不是类:

import React, { useState, useEffect } from 'react';
import { connect } from 'react-redux';
import BigHeader from './bigHeader';
import SmallHeader from './smallHeader';

const useWindowWidth = () => {
  function determineWidth() {
    const width = window.innerWidth;
    setWindowWidth(width);
  }
  const [windowWidth, setWindowWidth] = useState(
    window.innerWidth
  );
  useEffect(() => {
    window.addEventListener('resize', determineWidth);

    return function() {
      window.removeEventListener('resize', determineWidth);
    };
  },[]);
  return windowWidth;
};

function useIsSmall() {
  const windowWidth = useWindowWidth();
  if (windowWidth < 1307) {
    return true;
  }
  return false;
}

function Header(props) {
  const isSmall = useIsSmall();
  return isSmall ? <SmallHeader /> : <BigHeader />;
}

// export default connect(mapStateToProps, page);
export default Header;

答案 1 :(得分:0)

您不能在函数外部使用hooks

您能否在功能中移动代码const [windowWidth, setWindowWidth] = useState(window.innerWidth);,然后再试一次。

答案 2 :(得分:0)

尝试使用React Native中的Dimensions,此代码应正常工作: 您还可以在每次调用函数isSmall()时更新windowWidth值:

import { Dimensions } from 'react-native'
const windowWidth = Dimensions.get('window').width;
const windowheight = Dimensions.get('window').height;

function isSmall() {
if(this.windowWidth < 1307){
    return true;
  }
  return false;
}

class Header  extends Component {

render() {
    return this.isSmall() ? <SmallHeader/> : <BigHeader/> 
    }
}

// export default connect(mapStateToProps, page);
export default Header;

答案 3 :(得分:0)

根据React文档:Hookshooks只能在功能组件内部使用

大致像这样

import React, { useState } from 'react';
import { Dimensions } from 'react-native'
const windowWidth = Dimensions.get('window').width;
const windowheight = Dimensions.get('window').height;

function Example() {

  const [windowWidth, setWindowWidth] = useState(window.innerWidth);

  //Return something
  return (
    <div>

    </div>
  );
}