【发布时间】:2017-03-17 14:05:16
【问题描述】:
我有一个奇怪的行为。一旦我将套接字连接添加到 react / redux 系统,我的主要组件总是会在下一个 Action 被调度时重新渲染。
我也有这种行为,当我再次单击导航链接(发送相同的路由操作)时, 即使我留在同一页面上,组件也会重新渲染。
任何人都可以在这里帮助我走上正轨吗? 非常感谢!
设置 反应 0.15.x 还原 反应路由器 v4 react-router-redux
app.jsx 和容器的应用结构:
class Root extends React.Component {
render() {
return (
<Provider store={store}>
<Router history={history}>
<Route path="/" component={RootContainer}>
<IndexRoute component={HomePage} />
<Route path="/start" component={StartPage} />
<Route path="*" component={NotFoundPage} />
</Route>
</Router>
</Provider>
);
}
}
RootContainer
class RootContainer extends React.Component {
...
componentWillMount() {
this.connectToSocket();
this.joinChannel();
}
componentWillUnmount() {
this.socket.disconnect();
}
...
connectToSocket() {
this.socket = new Socket('/socket');
this.socket.connect();
this.socket.onOpen(() => {
this.props.connectState(); // ACTION CALL
});
this.socket.onError((err) => {
this.props.disconnectState(err); // ACTION CALL
}
}
...
减速器
【问题讨论】:
-
简短的版本是一些东西在不断地改变你的应用程序的状态。如果没有看到你的减速器,很难说到底是什么,但套接字会定期发送数据(保持活动状态或其他)。您可能只想在套接字遇到有趣的事情时更改状态。
-
感谢@RobDrimmie。我认为组件仅在状态更改时才会更改,并且仅重新渲染需要重新渲染的部分?附言连接状态必须保持不变并且很有趣,因为我们正在建立一个聊天。因此,当您断开连接时,我们需要通知和 UI 锁定。
-
你说得对,组件的 render() 函数只会在状态改变时被调用。由于您的电话经常被调用,因此状态正在发生很大变化。如果没有看到你的套接字处理函数或减速器,很难推测什么正在改变状态。我推测处理套接字的任何东西都对不断变化的状态负责。
标签: reactjs redux react-router react-redux