javascript - React 组件重新安装在另一个组件上的 props 更改
问题描述
我有一个 react-router-redux 应用程序,在所有页面顶部都有一个 voip 呼叫处理栏。voip bar 有一个计时器,它以每秒递增时间的间隔计算通话时间。
出于某种原因,每次 voip bar 重新渲染导致道具更改时,显示的页面(使用反应路由器)都会重新安装。我不知道为什么,因为 voip 栏甚至不是页面的子/父。
我真的不知道为什么会这样。我认为也许每次道具更改时路线都会发生变化,从而导致重新安装,但这不是问题。
布局:
<div className={classes.layout} id='layout'>
<Header isAuthenticated={this.props.isAuthenticated} username={this.props.username} />
<VoipBar />
<main className={classes.content} id='page-wrap'>
{this.props.children}
</main>
{/* <Footer /> */}
</div>
如您所见,VoipBar 不是页面的父级(页面是主标记内的子级)。
被调用的间隔是每秒调度一个动作的间隔。该动作的减速器是这样的:
case actionTypes.UPDATE_PHONE_TIMER:
return {
...state,
seconds: state.seconds + 1,
time: formatTime(state.seconds + 1)
}
我以这种方式在 VoipBar 组件中使用“时间”:
<div className={classes.twilioLog} style={{color: this.props.logColor}}>{`${this.props.twilioLog}${this.props.time ? `: ${this.props.time}` : '' }`}</div>
综上所述,voipbar上的定时器应该会根据通话时间每秒更新一次,完全不影响页面。现在每次 voipbar 更新时,整个页面都会重新安装。
编辑:我发现如果我删除我包装我的页面的 HOC,页面不再重新呈现。出于某种原因,现在 HOC 会在每次 voipbar 道具更改时重新渲染。HOC 用于身份验证(纯前端)。我仍然不明白那里发生了什么。这是我的 HOC:
import React from 'react';
import { connect } from 'react-redux';
import * as actions from '../../store/actions';
export default function (ComposedComponent) {
class Authenticate extends React.Component {
componentDidMount() {
if (!this.props.username || !this.props.role || !this.props.siteAccess) this.props.logout();
}
render() {
return <ComposedComponent {...this.props} />
}
}
const mapStateToProps = (state) => {
return {
username: state.auth.username,
role: state.auth.role,
siteAccess: state.auth.siteAccess
};
};
const mapDispatchToProps = dispatch => {
return {
logout: () => dispatch(actions.logout())
};
};
return connect(mapStateToProps, mapDispatchToProps)(Authenticate);
};
相关路线:
<Route path='/profile/person/:personId' component={withAuth(PersonProfile)} />
解决方案
您可以尝试使用以下shouldComponentUpdate()
方法:
https://reactjs.org/docs/react-component.html#shouldcomponentupdate
React 的文档说:
shouldComponentUpdate(nextProps, nextState)
用于shouldComponentUpdate()
让 React 知道组件的输出是否不受当前状态或道具变化的影响。默认行为是在每次状态更改时重新渲染,并且在绝大多数情况下,您应该依赖默认行为。
shouldComponentUpdate()
当接收到新的道具或状态时,在渲染之前调用。默认为真。初始渲染或使用 forceUpdate() 时不会调用此方法。
推荐阅读
- c# - 将字典添加到 json 文件时,字典中的最后一个条目会覆盖第一个写入的条目
- c# - 在服务结构中登录时 NService 总线访问被拒绝
- c++ - 即使在设置 SO_REUSEADDR 和 SO_REUSEPORT 之后,bind() 偶尔也会失败,地址已在使用中
- laravel - 如何比较laravel中的碳日期?
- r - XTS 分裂的艰难时期
- android - 按钮列表
- python - 打印具有一组有效数字的浮点数(非科学)
- python - Django-CMS:django admin 中的 PlaceholderField
- java - 如何找到maven依赖导入的jar的用法?
- julia - JuMP 和 Ipopt 出错