相关疑难解决方法(0)

使用 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

}
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作为依赖项传递,但是效果将在每次渲染上运行,而不仅仅是一次。或者使用引用,但这很难维护。 …

javascript state reactjs react-hooks use-effect

12
推荐指数
3
解决办法
2246
查看次数

如何在获取数据后设置状态React hook

代码

在此输入图像描述

结果:状态中没有数据

在此输入图像描述
请帮助我,谢谢!

setstate reactjs react-hooks

1
推荐指数
1
解决办法
1万
查看次数

标签 统计

react-hooks ×2

reactjs ×2

javascript ×1

setstate ×1

state ×1

use-effect ×1