lau*_*ent 12 javascript state reactjs react-hooks use-effect
使用常规的 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
}
Run Code Online (Sandbox Code Playgroud)
在 React Hooks 中,可以这样写:
function NoteEditor {
const [noteId, setNoteId] = useState(123);
useEffect(() => {
return () => {
logger('This note has been closed: ' + noteId); // bug!!
}
}, [])
return '...';
}
Run Code Online (Sandbox Code Playgroud)
返回的内容useEffect只会在组件卸载之前执行一次,但是状态(如上面的代码中所示)将是陈旧的。
一种解决方案是noteId作为依赖项传递,但是效果将在每次渲染上运行,而不仅仅是一次。或者使用引用,但这很难维护。
那么是否有任何推荐的模式可以使用 React Hook 来实现这一点?
使用常规 React,可以从组件中的任何位置访问状态,但是使用钩子似乎只有复杂的方式,每种方式都有严重的缺点,或者我可能只是遗漏了一些东西。
有什么建议吗?
小智 30
useRef()来救援。
由于ref是可变的并且在组件的生命周期内存在,因此我们可以在更新时使用它来存储当前值,并且仍然可以通过 ref 的 value .current属性在useEffect的清理函数中访问该值。
因此,每当状态发生变化时,都会有一个额外的useEffect()来保持 ref 的值更新。
示例片段
const [value, setValue] = useState();
const valueRef = useRef();
useEffect(() => {
valueRef.current = value;
}, [value]);
useEffect(() => {
return function cleanup() {
console.log(valueRef.current);
};
}, []);
Run Code Online (Sandbox Code Playgroud)
感谢https://www.timveletta.com/blog/2020-07-14-accessing-react-state-in-your-component-cleanup-with-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;
Run Code Online (Sandbox Code Playgroud)
应用程序
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>
);
}
Run Code Online (Sandbox Code Playgroud)
小智 5
我想附和一个答案,以防其他人遇到这个问题。如果您在 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'
/>
</>
);
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2246 次 |
| 最近记录: |