简体   繁体   中英

Force re-render in react functional component

I'm trying to update ReactDom when a function is called,

function showMessage(message, config) {
  ReactDOM.render(
    <Message message={message.body} />,
    document.getElementById(config.targetElementId)
  );
}

In the message component,

export default function Message({ message }) {
  const [open, setIsOpen] = useState(true);

  useEffect(() => {
    setIsOpen(true);
  }, [message]);

I'm using a useEffect to change the setIsOpen to true when the message changes. I want the component to call this useEffect every time showMessage(message, config) function is called. Now, the component is only re rendering if the message text is changed. message is a string like "Example string". If I'm calling the function with showMessage("Example string", config) multiple times, it does not call the useEffect. Only if I make a change in the string, showMessage("Example stringssss", config), it re-renders. How do I force re render each time the showMessage function is called?

You just add a props trigger is an object. So the component will always re-render

function showMessage(message, config) {
  ReactDOM.render(
    <Message message={message.body} trigger={{}} />,
    document.getElementById(config.targetElementId)
  );
}

function Message({ message, trigger })

  useEffect(() => {
    setIsOpen(true);
  }, [message, trigger]);

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