问题描述
我正在构建一个 PhotoViewer,它可以在用户向左或向右按下时更改照片.我正在使用 React、Redux、react-router 和 react-router-redux.当用户向左或向右按下时,我会做两件事,我使用 this.context.replace()
更新 url 并发送一个动作来更新当前查看的照片,this.props.dispatch(setPhoto(photoId))
.我正在订阅状态更改以进行调试.
I am building a PhotoViewer that changes photos when the user presses left or right. I am using React, Redux, react-router, and react-router-redux. When the user presses left or right, I do two things, I update the url using this.context.replace()
and I dispatch an action to update the currently viewed photo, this.props.dispatch(setPhoto(photoId))
. I am subscribing to state changes for debugging.
以上每一行都会触发一个新的状态变化.分派操作会更新商店,因为我更新了 currentlyViewedPhoto
,更新 url 会更新商店,因为 react-router-redux 会更新商店中的 url.当我分派动作时,在第一个重新渲染周期中,组件的 render
函数被调用两次.在第二个重新渲染周期中,组件的 render
函数被调用一次.这是正常的吗?相关代码如下:
Each of the above lines triggers a new state change. Dispatching an action updates the store since I update the currentlyViewedPhoto
and updating the url updates the store because react-router-redux updates the url in the store. When I dispatch the action, in the first rerendering cycle, the component's render
function gets called twice. In the second rerendering cycle, the component's render
function gets called once. Is this normal? Here is the relevant code:
class PhotoViewer extends Component {
pressLeftOrRightKey(e) {
... code to detect that left or right arrow was pressed ...
// Dispatching the action triggers a state update
// render is called once after the following line
this.props.dispatch(setPhoto(photoId)) // assume photoId is correct
// Changing the url triggers a state update
// render is called twice
this.context.router.replace(url) // assume url is correct
return
}
render() {
return (
<div>Test</div>
)
}
}
function select(state) {
return state
}
export default connect(select)(PhotoViewer)
render 被调用 3 次这正常吗?这似乎有点矫枉过正,因为 React 必须对 DOM 进行三遍差异.我想这并不重要,因为什么都没有改变.我是此工具集的新手,因此请随时提出有关此问题的更多问题.
Is this normal that render is called three times? It seems like overkill because React will have to do the DOM diffing three times. I guess it won't really matter because nothing has changed. I am new to this toolset, so feel free to ask any more questions about this problem.
推荐答案
我认为这是正常的.如果您没有明显的性能问题,我不会出汗.如果性能开始成为问题,您可以考虑覆盖 shouldComponentUpdate
生命周期方法,如果您确定某些状态更改不会更改呈现的组件.
I would assume that this is normal. If you aren't having noticeable performance issues, I wouldn't sweat it. If performance begins to be a problem, you can look into overriding the shouldComponentUpdate
lifecycle method if you are certain that certain state changes won't change the rendered component.
如果您只需要在 shouldComponentUpdate
生命周期中进行浅层比较,您还可以考虑扩展 React.PureComponent
而不是 React.Component
方法.更多信息请此处.
You could also look into extending React.PureComponent
instead of React.Component
if you only need shallow comparison in your shouldComponentUpdate
lifecycle method. More info here.
这篇关于推送新 URL 时多次调用 React 组件渲染的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论