简体   繁体   中英

Convert class component to functional components using hooks

I am trying to convert this class component to functional component using hooks

import React, { Component, cloneElement } from 'react';

class Dialog extends Component {
    constructor(props) {
        super(props);
        this.id = uuid();       
   }
   render(){
     return ( <div>Hello Dialog</div> );
  }
}

This component is initiated with a specific ID because I may have to use multiple instances of them. How can I achieve this if I use functional component?

One solution would be to use useEffect to create your ID at the first render, and store it in the state:

const Dialog = () => {
    const [id, setId] = useState(null);

    useEffect(() => {
        setId(uuid())
    }, [])

    return <div>Hello Dialog</div>
}

Giving an empty array as the second parameter of useEffect makes it unable to trigger more than once.

But another extremely simple solution could be to just... create it outside of your component:

const id = uuid();

const Dialog = () => {
    return <div>Hello Dialog</div>
}

You may store it in state:

const [id] = useState(uuid()); // uuid will be called in every render but only the first one will be used for initiation 

// or using lazy initial state
const [id] = useState(() => uuid()); // uuid will only be called once for initiation 

You may also store it in React ref:

const id = useRef(null);
if(!id.current) {
    // initialise 
    id.current = uuid();
}
// To access it’s value
console.log(id.current);

Any instance property becomes a ref pretty much, and you would access idRef.current in this case for the id

function Dialog() {
  const idRef = useRef(uuid())
  return <div>Hello Dialog</div>
}

Thank you all, your solutions works well. I also try this solution and I find it OK too: replace this.id with Dialog.id . Is there any downside with this solution?

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