我正在构建一个PhotoViewer,当用户按下左键或右键时,它可以更改照片.我正在使用React、Redux、React router和React router Redux.当用户按下左键或右键时,我会做两件事,使用this.context.replace()
更新url,并发送一个操作来更新当前查看的照片this.props.dispatch(setPhoto(photoId))
.我订阅状态更改以进行调试.
以上每一行都会触发一个新的状态更改.因为我更新了currentlyViewedPhoto
,所以发送一个操作会更新存储,而更新url会更新存储,因为react router redux会更新存储中的url.在第一个重新排序循环中,当我分派操作时,组件的render
函数会被调用两次.在第二个重新渲染周期中,组件的render
函数被调用一次.这正常吗?以下是相关代码:
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)
渲染调用三次是正常的吗?这似乎有些过分,因为React将不得不进行三次DOM扩散.我想这并不重要,因为一切都没有改变.我是这个工具集的新手,所以请随意询问更多关于这个问题的问题.