反对使用componentWillRecieveProps,并提倡使用getDerivedStateFromProps。
但是,当道具被更改时,componentWillRecieveProps会被调用,但是即使在任何状态变化时,getDerivedStateFromProps也会被调用。
我的要求是重置状态的道具改变。我怎么才能知道道具真的变了。
我不赞成在状态中存储道具值,因为它会不必要地使状态变得更大,而且我仍然没有考虑到状态管理(Redux或上下文API)。
请指教
发布于 2018-06-21 16:21:40
如果道具真的变了我怎么知道。
比较以前的道具和新的道具。
对于最简单的用例,只需使用componentDidUpdate(),并进行道具比较:
componentDidUpdate(prevProps) {
// Typical usage (don't forget to compare props):
if (this.props.userID !== prevProps.userID) {
this.fetchData(this.props.userID);
}
}根据反应医生的说法,在componentDidUpdate()中执行副作用或setState()是可以的。
而setState()会导致重呈现,影响构件的性能.当本例中的性能实际上是一个问题时,请继续阅读:https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html#when-to-use-derived-state
https://stackoverflow.com/questions/50971478
复制相似问题