【发布时间】:2016-05-10 06:37:51
【问题描述】:
我正在构建一个 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)
render 被调用 3 次是正常的吗?这似乎有点矫枉过正,因为 React 必须对 DOM 进行 3 次 diff。我想这并不重要,因为什么都没有改变。我是这个工具集的新手,所以请随时询问有关此问题的更多问题。
【问题讨论】:
-
我遇到了链接中没有斜杠的问题。如果我有
<Link to="foo">,React 路由器(不使用 redux)会从#foo“重定向”到#/foo并导致额外的渲染。将斜线添加到链接修复它。这是使用 hashHistory。
标签: javascript reactjs react-router redux