Cuando usé el mismo método en otro proyecto, funcionó bien, pero decidí usar el mismo método para mi proyecto actual, entonces tengo un problema con lo siguiente
react-dom.development.js:14724 Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons: 1. You might have mismatching versions of React and the renderer (such as React DOM) 2. You might be breaking the Rules of Hooks 3. You might have more than one copy of React in the same app See some tips for tips about how to debug and fix this problem. at Object.throwInvalidHookError (react-dom.development.js:14724:13) at useState (react.development.js:1497:21)A continuación se muestra el nombre de mi primer componente GetWindowWidth.js . este componente está relacionado con la aplicación de la pantalla para el escritorio, la pestaña y la pantalla de mob GetWindowWidth.js
import {useState,useEffect} from "react"; const GetWindowWidth = () => { const [width, setWidth] = useState(window.innerWidth); useEffect(() => { window.addEventListener("resize", updateWidth); return () => window.removeEventListener("resize", updateWidth); }); const updateWidth = () => { setWidth(window.innerWidth); }; return width; } export default GetWindowWidth;A continuación hay otro componente en el que intento llamar al componente anterior para aplicar el ancho de pantalla. OtroComponente.js
import React, { Component } from 'react' import GetWindowWidth from './GetWindowWidth'; export class AnotherComponent extends Component { render() { const width = GetWindowWidth(); return ( <div color={width<600? '#161625':"#f3990f"}>UserCatalogTwo</div> ) } } export default AnotherComponentNo sé por qué viene esto, incluso si está trabajando en otros proyectos.
GetWindowWidth es un gancho , no un componente , ya que no representa nada. (Y por esa razón, su nombre debe comenzar con use ). No puede usar ganchos en componentes de clase. Tendrá que volver a escribir el componente de clase como un componente de función o escribir una versión sin enlace de GetWindowWidth .
Por ejemplo, podría tener un módulo con una función que configura el controlador de cambio de tamaño:
// watchwidth.js export function watchWidth(callback) { const handler = () => { callback(window.innerWidth); }; window.addEventListener("resize", handler); return () => { window.removeEventListener("resize", handler); }; }...luego importarlo:
import { watchWidth } from "./watchwidth.js";... y úsalo en tu componente de clase:
componentDidMount() { this.stopWatchingWidth = watchWidth(width => this.setState({width})); } componentWillUnmount() { this.stopWatchingWidth(); }Eso es improvisado y no probado, pero te da una idea.