Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

137
Vistas
How can I rewrite part of the component to react hooks

tell me, I want to rewrite the component written on the methods of the life cycle on hooks, but it does not come out exactly in this place, it does not work as it should. How to rewrite it correctly?

componentDidMount() {
    this.updateUser();
}
componentDidUpdate(prevProps){
    if (this.props.userId !== prevProps.userId) {
        this.updateUser();
        console.log('update')
    }
}

updateUser = () => {
    const {userId} = this.props;
    if (!userId) {
        return;
    }
    this.onUserLoading();
    this.API
            .getUser(userId)
            .then(this.onUserLoaded)
            .catch(this.onError)
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

i have modified with react new hooks,

componentDidMount means useEffect(()=>{},[]) componentDidUpdate means useEffect((prev)=>{},[YOUR UPDATE DATA VARIABLE])

this will look like this way now, your function is like below,

updateUser = () => {
  if (!userId) {
      return;
  }
  this.onUserLoading();
  this.API
          .getUser(userId)
          .then(this.onUserLoaded)
          .catch(this.onError)
}

this will be converted functional component,

const [userId,setUserId] = useState(props.userId); // way 1
//const userId = {props}; // way 2

useEffect((prevProps)=>{
  updateUser();
  if(userId !== prevProps.userId){
    updateUser();
    console.log('update')
  }

},[userId, updateUser])  
about 4 years ago · Juan Pablo Isaza Denunciar

0

Please note that the effect depends on updateUser and the callback passed to useEffect does not get any arguments. Here is a working example:

const User = React.memo(function User({ userId }) {
  const [userResult, setUserResult] = React.useState("");
  //create this function only on mount
  const onUserLoaded = React.useCallback(
    (result) => setUserResult(result),
    []
  );
  //do not re create this function unless userId changes
  const onUserLoading = React.useCallback(() => {
    setUserResult(`user loading for ${userId}`);
    setTimeout(
      () => onUserLoaded(`result for user:${userId}`),
      1000
    );
  }, [userId, onUserLoaded]);
  //do not re create this function unless userId
  // or onUserLoading changes, onUserLoading only
  // changes when userId changes
  const updateUser = React.useCallback(() => {
    if (!userId) {
      return;
    }
    onUserLoading();
  }, [onUserLoading, userId]);
  //run the effect when updateUser changes
  //  updateUser only changes when userId changes
  React.useEffect(() => updateUser(), [updateUser]);
  return <div>user result:{userResult}</div>;
});
const App = () => {
  const [userId, setUserId] = React.useState(1);
  return (
    <div>
      <button onClick={() => setUserId(userId + 1)}>
        Change User ID
      </button>
      <User userId={userId} />
    </div>
  );
};

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>

<div id="root"></div>

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda