【发布时间】:2019-09-21 23:42:27
【问题描述】:
我面临以下问题:
在处理状态的 React 组件中,有一个与 socket.io 的 websocket 连接。每当我收到一些事件时,我应该做一些操作并更新组件的状态。示例:
socket.on('some event', () => {
this.aMethod() // this method calls setState()
})
问题是出现以下消息:
Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.
但我不在任何地方使用componentWillUnmount 方法。并且组件没有卸载。
如果我将 aMethod 替换为 this.props.aMethod() 并更新将起作用的父组件的状态( aMethod 存在于两个组件中)。问题是这个组件很大,因为它是一个容器,将所有状态移动到父级并使用道具会导致大量重写..
这让我想到应用的反应路线可能存在一些问题。
父组件有以下路由(概念上):
<Switch>
<Route exact path={'/user/:id'} render={(props) => <User />} />
<Route exact path={'/users'} render={(props) => <User />} />
</Switch>
我使用render 而不是component 因为我需要传递一些方法作为道具。 React 和 react-router-dom 是 16.x 和 5.0.0 的最新版本。
是否有可能以某种方式“冻结”组件的第一个实例,然后 url 发生变化,我无法再更新状态?如果我在componentWillUnmount() 中控制台记录一条消息,我看不到它正在卸载。
任何想法将不胜感激!
欢迎提问。
【问题讨论】:
-
请添加完整代码
标签: javascript reactjs socket.io react-router react-state