Aquí está la interfaz de usuario
Cuando hago clic en el primer botón, luego hago clic en el segundo botón, muestra el valor 1, pero espero que muestre el valor 2, ya que configuré el valor en 2. ¿Cuál es el problema y cómo debo solucionarlo?
Aquí está el código:
import { StrictMode } from "react"; import { createRoot } from "react-dom/client"; import React, { useState, useEffect, useMemo, useRef, useCallback } from "react"; const App = () => { const [channel, setChannel] = useState(null); const handleClick = useCallback(() => { console.log(channel); }, [channel]); const parentClick = () => { console.log("parent is call"); setChannel(2); }; useEffect(() => { setChannel(1); }); return ( <div className="App"> <button onClick={parentClick}>Click to SetChannel 2</button> <button onClick={handleClick}>Click to ShowChannel 2</button> </div> ); }; const rootElement = document.getElementById("root"); const root = createRoot(rootElement); root.render(<App />);Aquí está la caja de códigos
Agregue una dependencia al gancho useEffect , si no agrega ninguna dependencia, simplemente se volverá a ejecutar en cada cambio de estado.
Cambia esto:
useEffect(() => { setChannel(1); });A esto:
useEffect(() => { setChannel(1); }, []);useEffect(() => { setChannel(1); });Se ejecuta en cada renderizado, por lo que siempre vuelve a 1
Su problema es que está configurando el valor del canal en 1 cada renderizado. Tienes 2 opciones.
this.setState({channel: 1}) en el método componentDidMount . class App extends React.Component { constructor(props) { super(props); this.state = {channel: 1}; } handleClick=(evt)=> { console.log(this.state.channel); } parentClick=(evt)=> { this.setState({channel: 2}); } render() { return ( <div className="App"> <button onClick={this.parentClick}>Click to SetChannel 2</button> <br /><br /> <button onClick={this.handleClick}>Click to ShowChannel 2</button> </div> ); } }PD: no está claro lo que está tratando de hacer y su sandbox es bastante diferente del código que ha publicado aquí.