如何防止内联函数绑定到旧状态值

如何防止内联函数绑定到旧状态值

本文介绍了如何防止内联函数绑定到旧状态值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个包含使用钩子的 React 组件的项目中,我试图了解如何正确避免调用绑定到旧状态值的回调.下面的例子说明了这个问题(但不是我正在处理的代码).

import React, { useState, useEffect } from "react";从react-dom"导入 ReactDOM;const 消息 = () =>{const [message, setMessage] = useState("");函数 doStuff() {控制台日志(消息);}useEffect(() => {设置间隔(doStuff,1000)}, []);返回 (<div>setMessage(e.target.value)}/><p><strong>{消息}</strong></p>

);};const rootElement = document.getElementById(root");ReactDOM.render(, rootElement);

这里的问题当然是 setInterval 将保持 doStuff 函数在第一次(也是唯一一次)调用效果时的状态.那时 message 状态是空的,因此,间隔函数将每秒打印一个空字符串,而不是实际在文本框中的消息.

在我的实际代码中,我有一些外部事件应该触发组件内部的函数调用,但它们也遇到了同样的问题.

我该怎么办?

解决方案

您应该useCallback 并将其作为依赖项传递给您的效果.

const doStuff = useCallback(() => {控制台日志(消息);}, [信息]);useEffect(() => {const 间隔 = setInterval(doStuff, 1000);返回 () =>清除间隔(间隔);//清理}, [做东西]);

这里当 message 被更新时,它会在 doStuff

中有它的新值

In a project with React components using hooks, I am trying to understand how to properly avoid calling callbacks that are bound to old state values. The below example illustrates the issue (but is not the code I am working on).

import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";

const Message = () => {
  const [message, setMessage] = useState("");

  function doStuff() {
    console.log(message);
  }

  useEffect(() => {
    setInterval(doStuff, 1000)
  }, []);

  return (
    <div>
      <input
        type="text"
        value={message}
        placeholder="Enter a message"
        onChange={e => setMessage(e.target.value)}
      />
      <p>
        <strong>{message}</strong>
      </p>
    </div>
  );
};

const rootElement = document.getElementById("root");
ReactDOM.render(<Message />, rootElement);

The problem here is of course that setInterval will keep the doStuff function as it was when the effect was called the first (and only time). And at that time the message state was empty and hence, the interval function will print an empty string every second instead of the message that is actually inside the text box.

In my real code, I am having external events that should trigger function calls inside the component, and they suffer this same issue.

What should I do?

解决方案

You should useCallback and pass it as a dependency to your effect.

const doStuff = useCallback(() => {
  console.log(message);
}, [message]);

useEffect(() => {
  const interval = setInterval(doStuff, 1000);
  return () => clearInterval(interval); // clean up
}, [doStuff]);

Here when message gets updated it will have its new value in the doStuff

这篇关于如何防止内联函数绑定到旧状态值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 02:51