简体   繁体   中英

how to hide a string on re-render in react

I have a button inside a functional component which on click displays a string. I want to know how to hide that string when the component is re-rendered or there is any state change.

<button onClick = {() => props.getstring (props.state)} >Click </button>
{props.state.string}

So, when I click this button, the string is displayed but it stays on the screen when there is a state change. I want to hide it when any state value changes.

you can use react life-cycle methods to do that. As you need to get component update event you can use getSnapshotBeforeUpdate

getSnapshotBeforeUpdate(prevProps, prevState) {
    // ...
}

You need a useEffect Hook (Added in React16.8) for this,

import React, { useState, useEffect } from 'react';

const [isHidden, setIsHidden] = useState(false);

useEffect(
  () => {
    setIsHidden(true);
  },
  [props.state],
);

//Now the setIsHidden will only be called when props.state changes.

and then you can hide string,

{!isHidden && props.state.string}

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