道具更新时在组件上调用自定义方法
Call custom method on component when props update
我有一个 YouTubeiFrame
反应组件,它呈现一个空的 div,然后使用 componentDidMount
将 YouTube iframe 播放器放入 div。一切正常。我在使用玩家的组件上定义了一个 cueVideo
方法
API 提示新视频:
cueVideo(videoId) {
this.player.cueVideoById(videoId)
}
在我的应用程序的不同位置,您可以单击按钮或其他一些操作来指示您想要播放新视频。当您执行此操作时,'currentVideo' 状态会通过 redux 更新,因此 YouTubeiFrame 组件会收到新的视频 ID 作为更新的道具。
我的问题是如何调用上面的 cueVideo
方法来响应更新的 prop。我考虑过使用 shouldComponentUpdate
来比较 this.props.currentVideo
和下一个道具
但是意识到这个方法真的应该 return true/false 所以渲染函数可以被调用。我想要做的就是在 currentVideo 属性更改时调用 cueVideo
- 我真的不需要重新渲染。
最好的方法是什么?
All I want to do is call cueVideo when the currentVideo prop changes - I don't really need to re-render.
当收到新的道具时,React 会自动调用 render()
来更新您的组件。一旦所有更新都刷新到 DOM,React 也会在您的组件上调用 componentDidUpdate()
,让您有机会响应更改。正如 the documentation 所说:
Use this as an opportunity to operate on the DOM when the component has been updated.
我建议这是根据需要调用您的代码的最佳位置。
我有一个 YouTubeiFrame
反应组件,它呈现一个空的 div,然后使用 componentDidMount
将 YouTube iframe 播放器放入 div。一切正常。我在使用玩家的组件上定义了一个 cueVideo
方法
API 提示新视频:
cueVideo(videoId) {
this.player.cueVideoById(videoId)
}
在我的应用程序的不同位置,您可以单击按钮或其他一些操作来指示您想要播放新视频。当您执行此操作时,'currentVideo' 状态会通过 redux 更新,因此 YouTubeiFrame 组件会收到新的视频 ID 作为更新的道具。
我的问题是如何调用上面的 cueVideo
方法来响应更新的 prop。我考虑过使用 shouldComponentUpdate
来比较 this.props.currentVideo
和下一个道具
但是意识到这个方法真的应该 return true/false 所以渲染函数可以被调用。我想要做的就是在 currentVideo 属性更改时调用 cueVideo
- 我真的不需要重新渲染。
最好的方法是什么?
All I want to do is call cueVideo when the currentVideo prop changes - I don't really need to re-render.
当收到新的道具时,React 会自动调用 render()
来更新您的组件。一旦所有更新都刷新到 DOM,React 也会在您的组件上调用 componentDidUpdate()
,让您有机会响应更改。正如 the documentation 所说:
Use this as an opportunity to operate on the DOM when the component has been updated.
我建议这是根据需要调用您的代码的最佳位置。