简体   繁体   English

如何在react中重新渲染时隐藏字符串

[英]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

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

You need a useEffect Hook (Added in React16.8) for this, 为此,您需要一个useEffect Hook (在React16.8中添加)

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}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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