我正在构建一个 PhotoViewer,它可以在用户向左或向右按下时更改照片。我正在使用 React、Redux、react-router 和 react-router-redux。当用户向左或向右按下时,我会做两件事,我使用更新 urlthis.context.replace()
并发送一个操作来更新当前查看的照片,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)
渲染被调用 3 次这正常吗?这似乎有点矫枉过正,因为 React 必须对 DOM 进行三遍差异。我想这并不重要,因为什么都没有改变。我是这个工具集的新手,所以请随时提出有关此问题的更多问题。