简体   繁体   中英

How to reset and re-render components using react hooks

I am new to React Hooks.

I have been working on re-rendering after the button is clicked.

My Example

From my example, there are two buttons. One is to increment the count and the other is to remove the content. When I click a remove button, the content becomes null in order to reset the count.

What I want to try is to display the new content with the new count which is zero when the render button is clicked.

However, the issue is when I click the render button, it shows nothing.

I believe that the reason is because I have set null to remove the content in my condition which is logically incorrect. I have looked at the other questions related to this problem, but I haven't found any proper way to solve it.

Can anybody help me to figure this out?

The state provenient from the useState hooks belong to the App component. What you're doing is conditionally rendering a part of this component based on your current App state. From what I get it you have to setCount(0) manually to have your state clean. It's not possible to deconstruct a component from the inside out. Using a useEffect you can check when the component is constructed and destructed.

useEffect(() => {
  console.log('constructed');
  return () => {
    console.log('destructed');
  }
}, []);

What I want to try is to display the new content with the new count which is zero when the render button is clicked.

You can use a React key on an abstracted component that when updated, informs React that it's a "new" component and the old one should be unmounted and the new one mounted, essentially resetting it.

Example:

const Counter = () => {
  const [count, setCount] = useState(0);

  return (
    <div>
      <h1>Hello CodeSandbox {count}</h1>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
};

Use the toggling render state to toggle a new React key so Counter is remounted with initial state.

function App() {
  const [render, setRender] = useState(true);

  return (
    <div className="App">
      <Counter key={render} />
      <button onClick={() => setRender(!render)}>
        remove
      </button>
    </div>
  );
}

Demo

编辑 how-to-reset-and-re-render-components-using-react-hooks

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