gpt4 book ai didi

react-native - DeviceEventEmitter 它已经听了两次

转载 作者:行者123 更新时间:2023-12-01 16:35:10 26 4
gpt4 key购买 nike

我不知道为什么当我触发事件时 DeviceEventEmitter.addListener 它已经发出一次但听了两次。

我有一个组件 底座 它已添加到每个屏幕中,例如

<View>
{this.props.children}
<ModalComponent />
</View>

模态组件 应该可以随时打开 模态可见 事件它被解雇了。
  constructor (props) {
super(props)
this.state = {
modalVisible: false
}
}

componentDidMount() {
DeviceEventEmitter.addListener('ModalVisible', this.onModalVisible)
}

componentWillUnmount () {
DeviceEventEmitter.removeListener('ModalVisible', this.onModalVisible)
}

onModalVisible = (args) => {
console.log(['ModalVisible', args]) // logging twice
this.setState({
modalVisible: args.visible
})
}

close () {
this.setState({
modalVisible: false
})
}

onRequestClose = () => {
this.close()
}

render() {
return (
<Modal animationType={'slide'} transparent={false} visible={this.state.modalVisible} onRequestClose={this.onRequestClose}>
...
</Modal>
)
}

我有一个服务器在需要时发出事件
  static show (data) {
console.log(['Service.show', data]) // only once
DeviceEventEmitter.emit('ModalVisible', { visible: true })
}

当 Service.show 被调用时,第一个日志只出现一次,但立即出现在 addListener 它被记录了两次。

我已经试过了
this.listener = DeviceEventEmitter.addListener(...)
this.listener.remove()


this.onModalVisible.bind(this)

但它给了我同样的问题。

除此之外,在模态被复制的同时,当我关闭时,我有两个模态要关闭。

我还尝试在没有父组件的新屏幕中加载所有这些,看看这是否可能是问题所在,mas no。它仍然。

最佳答案

我在使用 socket.io 触发/注册两次事件时遇到了同样的问题,我的问题是由于我在 DidMount 方法上添加了 eventListeners。但是由于我的组件安装了多个,因此它也多次添加了 eventListeners。

我的猜测是您多次使用相同的组件,因此多次添加相同的 eventListener。尝试将您的 eventsListener 添加到另一个只会被调用一次的地方。

关于react-native - DeviceEventEmitter 它已经听了两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47436466/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com