如何卸载 React 功能组件?

rob*_*ear 1 reactjs react-state

我已经构建了几个模态作为 React 功能组件。它们通过isModalOpen模态关联上下文中的布尔属性显示/隐藏。这非常有效。

Now, for various reasons, a colleague needs me to refactor this code and instead control the visibility of the modal at one level higher. Here's some sample code:

import React, { useState } from 'react';
import Button from 'react-bootstrap/Button';
import { UsersProvider } from '../../../contexts/UsersContext';
import AddUsers from './AddUsers';

const AddUsersLauncher = () => {
  const [showModal, setShowModal] = useState(false);

  return (
    <div>
      <UsersProvider>
        <Button onClick={() => setShowModal(true)}>Add Users</Button>
        {showModal && <AddUsers />}
      </UsersProvider>
    </div>
  );
};

export default AddUsersLauncher;
Run Code Online (Sandbox Code Playgroud)

This all works great initially. A button is rendered and when that button is pressed then the modal is shown.

The problem lies with how to hide it. Before I was just setting isModalOpen to false in the reducer.

When I had a quick conversation with my colleague earlier today, he said that the code above would work and I wouldn't have to pass anything into AddUsers. I'm thinking though that I need to pass the setShowModal function into the component as it could then be called to hide the modal.

But I'm open to the possibility that I'm not seeing a much simpler way to do this. Might there be?

McR*_*ist 5

To call something on unmount you can use useEffect. Whatever you return in the useEffect, that will be called on unmount. For example, in your case

const AddUsersLauncher = () => {
  const [showModal, setShowModal] = useState(false);


  useEffect(() => {
    return () => {
      // Your code you want to run on unmount.
    };
  }, []); 


  return (
    <div>
      <UsersProvider>
        <Button onClick={() => setShowModal(true)}>Add Users</Button>
        {showModal && <AddUsers />}
      </UsersProvider>
    </div>
  );
};
Run Code Online (Sandbox Code Playgroud)

Second argument of the useEffect accepts an array, which diff the value of elements to check whether to call useEffect again. Here, I passed empty array [], so, it will call useEffect only once.

如果你传递了其他东西,比如说,showModal在数组中,那么每当showModal值改变时,useEffect 将调用,如果指定,将调用返回的函数。


小智 1

如果您想保留showModal状态变量 inAddUsersLauncher并从内部更改它 AddUsers,那么是的,您必须传递setShowModalto的引用AddUsers。React 中的状态管理在双向数据流中可能会变得混乱,因此我建议您查看Redux来存储和更改多个组件共享的状态