React Hooks useState+useEffect+event 给出过时的状态

IT技术 javascript reactjs codemirror eventemitter react-hooks
2021-03-02 18:27:51

我正在尝试将事件发射器与 ReactuseEffect一起使用useState,但它总是获得初始状态而不是更新状态。如果我直接调用事件处理程序,即使使用setTimeout.

如果我将值传递给useEffect()第二个参数,它会使其工作,但是这会导致每次值更改时重新订阅事件发射器(由击键触发)。

我究竟做错了什么?我试过useState, useRef, useReducer, 和useCallback,但没有任何工作。

这是一个复制品:

import React, { useState, useEffect } from "react";
import { Controlled as CodeMirror } from "react-codemirror2";
import "codemirror/lib/codemirror.css";
import EventEmitter from "events";

let ee = new EventEmitter();

const initialValue = "initial value";

function App(props) {
  const [value, setValue] = useState(initialValue);

  // Should get the latest value, both after the initial server load, and whenever the Codemirror input changes.
  const handleEvent = (msg, data) => {
    console.info("Value in event handler: ", value);
    // This line is only for demoing the problem. If we wanted to modify the DOM in this event, we would instead call some setState function and rerender in a React-friendly fashion.
    document.getElementById("result").innerHTML = value;
  };

  // Get value from server on component creation (mocked)
  useEffect(() => {
    setTimeout(() => {
      setValue("value from server");
    }, 1000);
  }, []);

  // Subscribe to events on component creation
  useEffect(() => {
    ee.on("some_event", handleEvent);
    return () => {
      ee.off(handleEvent);
    };
  }, []);

  return (
    <React.Fragment>
      <CodeMirror
        value={value}
        options={{ lineNumbers: true }}
        onBeforeChange={(editor, data, newValue) => {
          setValue(newValue);
        }}
      />
      {/* Everything below is only for demoing the problem. In reality the event would come from some other source external to this component. */}
      <button
        onClick={() => {
          ee.emit("some_event");
        }}
      >
        EventEmitter (doesnt work)
      </button>
      <div id="result" />
    </React.Fragment>
  );
}

export default App;

这是一个代码沙箱,在App2

https://codesandbox.io/s/ww2v80ww4l

App组件有 3 种不同的实现 - EventEmitter、pubsub-js 和 setTimeout。只有 setTimeout 有效。

编辑

为了阐明我的目标,我只是希望 inhandleEvent的值在所有情况下都与 Codemirror 值相匹配。单击任何按钮时,应显示当前的 codemirror 值。而是显示初始值。

3个回答

value在事件处理程序中是陈旧的,因为它从定义它的闭包中获取它的值。除非我们在每次value更改时重新订阅一个新的事件处理程序,否则它不会获得新值。

解决方案 1:为发布效果设置第二个参数[value]这使得事件处理程序获得正确的值,但也会导致效果在每次击键时再次运行。

解决方案 2:使用 aref将最新的存储value在组件实例变量中。然后,创建一个效果,每次value状态改变时只更新这个变量在事件处理程序中,使用ref,而不是value

const [value, setValue] = useState(initialValue);
const refValue = useRef(value);
useEffect(() => {
    refValue.current = value;
});
const handleEvent = (msg, data) => {
    console.info("Value in event handler: ", refValue.current);
};

https://reactjs.org/docs/hooks-faq.html#what-c​​an-i-do-if-my-effect-dependencies-change-too-often

看起来该页面上还有一些其他解决方案也可能有效。非常感谢@Dinesh 的帮助。

实际上,useState此处应该有 的第二个参数[],否则在不需要时每次渲染时都会调用它。
2021-05-07 18:27:51
刚刚注意到在 React Hooks RFC 的缺点部分明确描述了这个用例:github.com/reactjs/rfcs/blob/master/text/...
2021-05-19 18:27:51

更新的答案。

问题不在于钩子。初始状态值被关闭并传递给 EventEmitter 并被一次又一次地使用。

直接在handleEvent. 相反,我们需要在发出事件时将它们作为参数传递。

import React, { useState, useEffect } from "react";
import { Controlled as CodeMirror } from "react-codemirror2";
import "codemirror/lib/codemirror.css";
import EventEmitter from "events";

let ee = new EventEmitter();

const initialValue = "initial value";

function App(props) {
  const [value, setValue] = useState(initialValue);
  const [isReady, setReady] = useState(false);

  // Should get the latest value
  function handleEvent(value, msg, data) {
    // Do not use state values in this handler
    // the params are closed and are executed in the context of EventEmitter
    // pass values as parameters instead
    console.info("Value in event handler: ", value);
    document.getElementById("result").innerHTML = value;
  }

  // Get value from server on component creation (mocked)
  useEffect(() => {
    setTimeout(() => {
      setValue("value from server");
      setReady(true);
    }, 1000);
  }, []);

  // Subscribe to events on component creation
  useEffect(
    () => {
      if (isReady) {
        ee.on("some_event", handleEvent);
      }
      return () => {
        if (!ee.off) return;
        ee.off(handleEvent);
      };
    },
    [isReady]
  );

  function handleClick(e) {
    ee.emit("some_event", value);
  }

  return (
    <React.Fragment>
      <CodeMirror
        value={value}
        options={{ lineNumbers: true }}
        onBeforeChange={(editor, data, newValue) => {
          setValue(newValue);
        }}
      />
      <button onClick={handleClick}>EventEmitter (works now)</button>
      <div id="result" />
    </React.Fragment>
  );
}

export default App;

这是一个有效的代码和框

我认为关键是,无论您从何处触发事件,发射器都应该包含有效载荷,而不是依赖来自外部来源的数据。也许,像 redux 这样的数据存储会有所帮助,因为它允许您在 React 组件之外获取存储数据。但正确的方法是设计一个实现,其中数据不依赖于外部来源并作为有效负载传递。
2021-04-21 18:27:51
@TonyR 我发现了这个问题。它与钩子或 React 无关。handleEvent方法以初始状态值关闭并传递给 EventEmitter 并且始终使用相同的值。关闭。我已经更新了解决方案。
2021-04-22 18:27:51
单击按钮时,事件处理程序中的值应与 codemirror 的当前值相同。
2021-04-25 18:27:51
谢谢你的帮助。我将您的代码放在一个新的沙箱中:codesandbox.io/s/oo159k4w5y ( App3)。它可以加载服​​务器值,但是目标也是获得 Codemirror 更改,因此如果您更改 codemirror 输入,您仍然会获得原始服务器值。我通过将事件处理程序置于以下状态使其以另一种方式工作:codesandbox.io/s/6jq3r6vnjw ( App)。想法?
2021-05-13 18:27:51
@TonyR 我不确定我是否正确理解了所需的功能。- 你所说的“作品”是什么意思?- 您所说的“不起作用”是什么意思?
2021-05-15 18:27:51

useCallback 应该在这里工作。

import React, { useState, useEffect, useCallback } from "react";
import PubSub from "pubsub-js";
import { Controlled as CodeMirror } from "react-codemirror2";
import "codemirror/lib/codemirror.css";
import EventEmitter from "events";

let ee = new EventEmitter();

const initialValue = "initial value";

function App(props) {
  const [value, setValue] = useState(initialValue);

  // Should get the latest value
  const handler = (msg, data) => {
    console.info("Value in event handler: ", value);
    document.getElementById("result").innerHTML = value;
  };

  const handleEvent = useCallback(handler, [value]);

  // Get value from server on component creation (mocked)
  useEffect(() => {
    setTimeout(() => {
      setValue("value from server");
    }, 1000);
  }, []);

  // Subscribe to events on component creation
  useEffect(() => {
    PubSub.subscribe("some_event", handleEvent);
    return () => {
      PubSub.unsubscribe(handleEvent);
    };
  }, [handleEvent]);
  useEffect(() => {
    ee.on("some_event", handleEvent);
    return () => {
      ee.off(handleEvent);
    };
  }, []);

  return (
    <React.Fragment>
      <CodeMirror
        value={value}
        options={{ lineNumbers: true }}
        onBeforeChange={(editor, data, newValue) => {
          setValue(newValue);
        }}
      />
      <button
        onClick={() => {
          ee.emit("some_event");
        }}
      >
        EventEmitter (works)
      </button>
      <button
        onClick={() => {
          PubSub.publish("some_event");
        }}
      >
        PubSub (doesnt work)
      </button>
      <button
        onClick={() => {
          setTimeout(() => handleEvent(), 100);
        }}
      >
        setTimeout (works!)
      </button>
      <div id="result" />
    </React.Fragment>
  );
}

export default App;

在此处检查代码和框https://codesandbox.io/s/react-base-forked-i9ro7