Home > Net >  How can I rewrite part of the component to react hooks
How can I rewrite part of the component to react hooks

Time:11-16

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)

CodePudding user response:

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])  

CodePudding user response:

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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related