我使用此代码,
参考:https://blog.csdn.net/lucky_ly/article/details/138096824
接收到发送过来的数据,为何会打印两次呢?
emitter目录:
emitter/index.ts
import type { Emitter } from 'mitt'
import mitt from 'mitt'
export default mitt() as Emitter<any>
组件A:
import { useEffect } from 'react'
import Emitter from '../../emitter'
function Index() {
useEffect(() => {
console.log('mounted') // 挂载后
}, [])
return <>
AAA
<button onClick={() => {
console.log('按钮被点击')
Emitter.emit('e1',{"name":"zhangsah=n"})
}
}>A发送信息到B</button>
</>
}
export default Index
组件B:
import { useEffect } from 'react'
import Emitter from '../../emitter'
function Index() {
useEffect(() => {
console.log('mounted') // 挂载后
Emitter.on('e1',(e)=>{
console.log('mitt test',e)
})
}, [])
return <>
BBB
</>
}
export default Index
点击A组件按钮的时候,B组件内打印了两次: