您不应直接在函数渲染周期内定义发射器实例。相反,您必须只创建和添加一次侦听器事件。
只创建一次listner,使用useRef;如果只添加一个listner,使用useEffect hook
示例代码
const App = props => {
const myEmitter = useRef(new EventEmitter());
const [counter, setCounter] = useState(0);
useEffect(() => {
myEmitter.current.on("event", msg => {
console.log("Parent received: " + msg);
});
}, []);
const Send = () => {
myEmitter.current.emit("event", "parent sending this message.");
};
return (
<Content>
<button onClick={Send}>emit</button>
<button onClick={() => setCounter(counter + 1)}>count {counter}</button>
<Child myEmitter={myEmitter.current} />
</Content>
);
};
import React, { useState, useEffect } from "react";
const Child = props => {
const [counter, setCounter] = useState(0);
useEffect(() => {
props.myEmitter.on("event", msg => {
console.log("Child received: " + msg);
});
}, [props.myEmitter]);
const Emit = () => {
props.myEmitter.emit("event", "child sending this message");
};
return (
<>
<button onClick={Emit}>child emit</button>
<button onClick={() => setCounter(counter + 1)}>
child count {counter}
</button>
</>
);
};
export default Child;
Demo