简体   繁体   中英

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)

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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM