使用 React Hooks 卸载组件时如何访问状态?

How to access state when component unmount with React Hooks?

使用常规的 React 可能会有这样的事情:

class NoteEditor extends React.PureComponent {

    constructor() {
        super();

        this.state = {
            noteId: 123,
        };
    }

    componentWillUnmount() {
        logger('This note has been closed: ' + this.state.noteId);
    }

    // ... more code to load and save note

}

在 React Hooks 中,可以这样写:

function NoteEditor {
    const [noteId, setNoteId] = useState(123);

    useEffect(() => {
        return () => {
            logger('This note has been closed: ' + noteId); // bug!!
        }
    }, [])

    return '...';
}

useEffect 返回的内容只会在组件卸载之前执行一次,但是状态(如上面的代码中所示)将是陈旧的。

一个解决方案是将 noteId 作为依赖项传递,但这样效果会 运行 在每个渲染上,而不仅仅是一次。或者使用引用,但这很难维护。

那么有没有推荐的模式来使用 React Hook 实现这个?

使用常规 React,可以从组件中的任何位置访问状态,但是使用 hooks 似乎只有复杂的方法,每种方法都有严重的缺点,或者我可能只是遗漏了一些东西。

有什么建议吗?

useState()useReducer() 的特殊形式,因此您可以替代完整的 reducer 来获取当前状态并解决闭包问题。

笔记编辑器

import React, { useEffect, useReducer } from "react";

function reducer(state, action) {
  switch (action.type) {
    case "set":
      return action.payload;
    case "unMount":
      console.log("This note has been closed: " + state); // This note has been closed: 201
      break;
    default:
      throw new Error();
  }
}

function NoteEditor({ initialNoteId }) {
  const [noteId, dispatch] = useReducer(reducer, initialNoteId);

  useEffect(function logBeforeUnMount() {
    return () => dispatch({ type: "unMount" });
  }, []);

  useEffect(function changeIdSideEffect() {
    setTimeout(() => {
      dispatch({ type: "set", payload: noteId + 1 });
    }, 1000);
  }, []);

  return <div>{noteId}</div>;
}
export default NoteEditor;

应用程序

import React, { useState, useEffect } from "react";
import "./styles.css";
import NoteEditor from "./note-editor";

export default function App() {
  const [notes, setNotes] = useState([100, 200, 300]);

  useEffect(function removeNote() {
    setTimeout(() => {
      setNotes([100, 300]);
    }, 2000);
  }, []);

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      {notes.map(note => (
        <NoteEditor key={`Note${note}`} initialNoteId={note} />
      ))}
    </div>
  );
}

useRef() 进行救援。

由于 ref 是可变的并且在组件的生命周期内存在,我们可以在更新时使用它来存储当前值,并且仍然可以在清理中访问该值我们的 useEffect 函数通过 ref 的值 .current 属性.

所以会有一个额外的 useEffect() 来在状态改变时保持 ref 的值更新。

示例片段

const [value, setValue] = useState();
const valueRef = useRef();

useEffect(() => {
  valueRef.current = value;
}, [value]);

useEffect(() => {
  return function cleanup() {
    console.log(valueRef.current);
  };
}, []);

感谢 https://www.timveletta.com/blog/2020-07-14-accessing-react-state-in-your-component-cleanup-with-hooks/ 的作者。深潜请参考此link。

我想插话回答这个问题,以防其他人遇到这个问题。如果您在 useEffect 卸载函数中需要多个值,请务必确保使用了正确的依赖项。所以接受的答案很好,因为它只是一个依赖项,但是开始包含更多的依赖项,它变得复杂了。你需要的 useRef 的数量失控了。因此,您可以做的是一个 useRef,它是卸载函数本身,并在您卸载组件时调用它:

import React, { useRef, useState, useContext, useCallback, useEffect } from 'react';
import { Heading, Input } from '../components';
import { AppContext } from '../../AppContext';

export const TitleSection: React.FC = ({ thing }) => {
  const { updateThing } = useContext(AppContext);
  const [name, setName] = useState(thing.name);
  const timer = useRef(null);
  const onUnmount = useRef();

  const handleChangeName = useCallback((event) => {
    setName(event.target.value);

    timer.current !== null && clearTimeout(timer.current);
    timer.current = setTimeout(() => {
      updateThing({
        name: name || ''
      });
      timer.current = null;
    }, 1000);
  }, [name, updateThing]);

  useEffect(() => {
    onUnmount.current = () => {
      if (thing?.name !== name) {
        timer.current !== null && clearTimeout(timer.current);
        updateThing({
          name: name || '',
        });
        timer.current = null;
      }
    };
  }, [thing?.name, name, updateThing]);

  useEffect(() => {
    return () => {
      onUnmount.current?.();
    };
  }, []);

  return (
    <>
      <Heading as="h1" fontSize="md" style={{ marginBottom: 5 }}>
        Name
      </Heading>
      <Input
        placeholder='Grab eggs from the store...'
        value={name}
        onChange={handleChangeName}
        variant='white'
      />
    </>
  );
};