Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

135
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda