componentDidUpdate 在第一次安装组件后未触发(React)
componentDidUpdate not firing after the first time the component is mounted (React)
我有一个功能,可以通过单击按钮在单个页面上切换 windows(组件)。
交换函数windows:
getProfileContent = () => {
var html = [];
if (this.state.content === "picks") {
html.push(<Picks picks={this.state.picks} deletePick={this.deletePick} />);
}
if (this.state.content === "api") {
html.push(<Admin admin="admin" />);
}
if (this.state.content === 'settings') {
html.push(<Settings />);
}
return html;
};
父组件初始加载时内容默认为"picks","Picks"组件第一次加载时一切正常,因为触发了下面的componentDidUpdate更新函数:
"Picks"组件更新函数:
componentDidUpdate(prevProps, prevState) {
console.log('here')
if (Object.keys(prevProps.picks).length !== Object.keys(this.props.picks).length) {
this.sortPicks();
}
}
但是,在通过 getProfileContent 交换 windows 并返回到 "Picks"组件componentDidUpdate函数没有被触发。我也曾尝试向 Picks 组件添加不同的 "key" 值,希望新道具会触发 componentDidUpdate,但没有成功。如果条件如此,我将控制台日志记录在外面,所以我知道无论条件如何,都不会调用 componentDidUpdate。感谢任何帮助,谢谢!
道具值可能没有改变,因此相同的道具值被传递下来,因此具有相同的长度。它很可能到达 componentDidUpdate()
挂钩,但条件 returns 为假,因此您不会进入 sortPicks()
函数。在不知道其余代码的情况下很难说。
这个问题已经在@lanxion 的帮助下解决了。基本上,组件第一次挂载时会调用 componentDidUpdate 函数,但这只是因为父组件更新并传入了新的 props。第二次安装组件时,父级已经具有正确的道具,因此仅调用 componentDidMount 而不是 componentDidUpdate。将代码放在 componentDidMount 和 componentDidUpdate 中(带条件)解决了我的问题,
我有一个功能,可以通过单击按钮在单个页面上切换 windows(组件)。
交换函数windows:
getProfileContent = () => {
var html = [];
if (this.state.content === "picks") {
html.push(<Picks picks={this.state.picks} deletePick={this.deletePick} />);
}
if (this.state.content === "api") {
html.push(<Admin admin="admin" />);
}
if (this.state.content === 'settings') {
html.push(<Settings />);
}
return html;
};
父组件初始加载时内容默认为"picks","Picks"组件第一次加载时一切正常,因为触发了下面的componentDidUpdate更新函数:
"Picks"组件更新函数:
componentDidUpdate(prevProps, prevState) {
console.log('here')
if (Object.keys(prevProps.picks).length !== Object.keys(this.props.picks).length) {
this.sortPicks();
}
}
但是,在通过 getProfileContent 交换 windows 并返回到 "Picks"组件componentDidUpdate函数没有被触发。我也曾尝试向 Picks 组件添加不同的 "key" 值,希望新道具会触发 componentDidUpdate,但没有成功。如果条件如此,我将控制台日志记录在外面,所以我知道无论条件如何,都不会调用 componentDidUpdate。感谢任何帮助,谢谢!
道具值可能没有改变,因此相同的道具值被传递下来,因此具有相同的长度。它很可能到达 componentDidUpdate()
挂钩,但条件 returns 为假,因此您不会进入 sortPicks()
函数。在不知道其余代码的情况下很难说。
这个问题已经在@lanxion 的帮助下解决了。基本上,组件第一次挂载时会调用 componentDidUpdate 函数,但这只是因为父组件更新并传入了新的 props。第二次安装组件时,父级已经具有正确的道具,因此仅调用 componentDidMount 而不是 componentDidUpdate。将代码放在 componentDidMount 和 componentDidUpdate 中(带条件)解决了我的问题,